Zhen
Zhen

Reputation: 4283

Creating objects in Lua from C code

I want to create a Agent class with defined functions in lua. So, If I have a lua file soldier.lua like:

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

From C code, I can load it, creating the Agent table like:

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

Now I want to create a fake object self from C to call Agent:init and a) the self.x line call a C function to register the data. And the line self.test() call correctly the lua funcion Agent:test. But I can't get it working.

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

Any ideas?

Upvotes: 0

Views: 604

Answers (1)

Zhen
Zhen

Reputation: 4283

Solved using:

  • Setting metatable on Agent after lua file execution
  • Using Agent as its own fake object when I call file functions:

After the call of lua_dofile(...) I put:

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

Then, the call to a the function Agent:init is done with:

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

Upvotes: 1

Related Questions