這幾天試圖在delphi中整合Lua,發現相關的資料相當少。
最早下載的Lua4Delphi(http://sourceforge.net/projects/lua4delphi/files/lua4delphi/)包已經廢棄很久了。連自帶的示例都無法正常運行。源碼中也有顯而易見的bug。所以繼續尋找可用的組件,找到了LuaDelphi 2010(http://blog.spreendigital.de/wp-content/uploads/2009/10/LuaDelphi2010-v1.3.zip) 這個組件可以正常運行,但有一個缺點:只能注冊類中的方法而無法注冊類本身。而且注冊的類方法必須遵循統一的函數原型。所以它也不是好的選擇。
后來找到了一個叫pLua的組件,發現它還是不錯的,支持注冊類,也支持動態注冊類實例。不過它是用Lazarus寫的,所以在函數指針上與delphi編譯器有差異,在pLuaObject.pas中,plua_pushFunction這個過程要改一下才能正常運行。具體就是把 addr := integer(p^); 改成 addr := integer(p);即可.
具體用法如下:
uses LuaWrapper,pLuaObject; Lua := TLua.Create(self); lua.Value['x'] := 100;//注冊變量 Lua.RegisterLuaMethod('ShowMessage', lua_ShowMessage);//注冊函數 RegisterLuaButton(Lua.LuaState);//注冊類 RegisterExistingButton(Lua.LuaState, 'btn', btn1);//注冊類實例 if FileExists('script.lua') then begin Lua.LoadFile('script.lua'); Lua.Execute; showmessage(inttostr(lua.Value['x']));//讀取變量 end; var ButtonInfo : TLuaClassInfo; function setButtonInfo : TLuaClassInfo; begin plua_initClassInfo(result); result.ClassName := 'TButton'; result.New := @newButton; plua_AddClassProperty(result, 'Caption', @GetCaption, @SetCaption); plua_AddClassProperty(result, 'Left', @GetLeft, @SetLeft); plua_AddClassProperty(result, 'Top', @GetTop, @SetTop); plua_AddClassProperty(result, 'Width', @GetWidth, @SetWidth); plua_AddClassProperty(result, 'Height', @GetHeight, @SetHeight); plua_AddClassProperty(result, 'Visible', @GetVisible, @SetVisible); plua_AddClassProperty(result, 'Enabled', @GetEnabled, @SetEnabled); plua_AddClassMethod(result, 'Click', @Click); end; procedure RegisterLuaButton(L: Plua_State); begin plua_registerclass(L, ButtonInfo); end; procedure RegisterExistingButton(L: Plua_State; InstanceName : AnsiString; Instance: TButton); begin TButtonDelegate.Create(plua_registerExisting(L, InstanceName, Instance, @ButtonInfo), Instance); end;