用C代码在Lua中创建对象

我想创建一个包含定义函数的 lua 类 Agent。因此,如果我有一个名为 soldier.lua 的 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 代码中,我可以加载它,如下创建 Agent table:

// 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());

现在我想从 C 中创建一个假对象 self,并调用 Agent:init 函数。 a)在 self.x 行中调用 C 函数来注册数据。并且 self.test() 行正确调用 lua 函数 Agent:test。 但是我无法让它正常工作。

例如:

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);

有什么建议吗?

点赞
用户824499
用户824499

解决方法:

  • 在 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 );
2013-02-21 16:02:37