2013-02-21 44 views
0

我想在lua中創建一個具有已定義函數的代理類。所以,如果我有soldier.lua像一個Lua文件:從C代碼在Lua中創建對象

function Agent:init() 
    io.write("Agent init\n") 
    if self then 
     self.x = 4 
     self:test() 
    end 
end 

function Agent:test() 
    io.write("Agent test\n") 
end 

從C代碼,我可以加載它,創建的代理表所示:

// create Agent class on Lua 
lua_newtable(L); 
lua_setfield(L, LUA_GLOBALSINDEX, "Agent"); 
// execute class file 
auto ret = luaL_dofile(L, filename.c_str()); 

現在我想從創建一個假的對象self C調用Agent:init和a)self.x行調用C函數來註冊數據。並且self.test()函數正確調用lua funcion Agent:test。但我無法得到它的工作。

E.g:

lua_getfield(L, LUA_GLOBALSINDEX, "Agent"); 
lua_getfield(L, -1, "init"); 
lua_newtable(L); 
lua_getfield(L, LUA_GLOBALSINDEX, "Agent"); 
lua_setmetatable(L, -2); 
lua_getfield(L, LUA_GLOBALSINDEX, "Agent"); 
lua_getmetatable(L, -1); 
lua_pushcfunction(L, testnewindex); 
lua_setfield(L, -2, "__newindex"); 
ret = lua_pcall(L, 1, 0, 0); 

任何想法?

+1

「但是,我可以得到它的工作」那麼,有什麼問題呢? :) – 2013-02-21 13:01:48

+0

@BartekBanachewicz傻了我,修正:)。問題和答案 – Zhen 2013-02-21 16:03:43

回答

1

使用解決:

  • LUA文件執行後Agent設置元表
  • 使用Agent作爲自己的假目標,當我打電話文件功能:

lua_dofile(...)電話,我把後:

lua_getfield(L, LUA_GLOBALSINDEX, "Agent"); 
luaL_newmetatable(L, "Agent"); 
lua_pushstring(L, "__newindex"); 
lua_pushcfunction(L, agent_newindex); 
lua_settable(L, -3); 
lua_pushstring(L, "__index"); 
lua_pushcfunction(L, agent_index); 
lua_settable(L, -3); 
lua_setmetatable(L, -2); 

然後,調用一個函數Agent:init與完成:

lua_getfield(L, LUA_GLOBALSINDEX, "Agent"); 
lua_getfield(L, -1, "init"); 
lua_getfield(L, LUA_GLOBALSINDEX, "Agent"); 
ret = lua_pcall(L, 1, 0, 0);