2011-10-19 44 views
2

創建表目前我在lua中有類似於使用表的OOP。Lua C API從表

TCharacterController = {} 
TCharacterController.speed = 10.0 
TCharacterController.axis = "x" 

function TCharacterController:new(o) 
    o = o or {} 
    setmetatable(o, self) 
    self.__index = self 
    return o 
end 

function TCharacterController:update() 
    --this is a function that is called by the C application 
end 

的概念是,我將創建連接到我的應用程序對象每個腳本實例的子對象

ScriptObj = TCharacterController:new() 

(這是一個遊戲)。所以我有一個實體層,所有的實體都有能力附加一個ScriptObj。我的想法是,腳本實際上是一個類,它也爲它所連接的每個實體實例化。

我的問題是,我如何使用C API實例化TCharacterController的實例?

回答

3

由於新的使用自參考語法糖,你需要通過自己的第一個參數,剩下的只是一個查找表中的函數調用:

lua_getglobal(L, "TCharacterController"); /* get the table */ 
lua_getfield(L, -1, "new"); /* get the function from the table */ 
lua_insert(L, -2); /* move new up a position so self is the first arg */ 
lua_pcall(L, 1, 1); /* call it, the returned table is left on the stack */ 
+0

謝謝你了。 –