0

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?

2
  • 1
    "But I can get it working" So what's the problem? :) Commented Feb 21, 2013 at 13:01
  • @BartekBanachewicz Silly me, fixed :). The question and the answer Commented Feb 21, 2013 at 16:03

1 Answer 1

1

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 );
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.