2

I'm integrating Lua in C++, and now I have this table that behaves as a 'class', and for some functions it needs a 'self' argument, which actually is the table. The Lua code:

a = {
numb = 5,

create = function(a)
    print(a);
end,

increment = function(self)
                            --self.numb = 6;
                            print(self.numb);
end,

decrement = function(self,i)
                            self.numb = self.numb-i;
                            print(self.numb);
end
};
b = a;

And the C++ bit to call the functions (I've got Lua running in C++)

luaL_openlibs(L);

luaL_dofile (L,"main.lua");

lua_getglobal(L, "a");
lua_getfield(L, -1, "increment");

string arg = "a";

lua_pushliteral(L,"a");

lua_pcall(L ,1,0,0);

printf(" \nI am done with Lua in C++.\n");

lua_close(L);

So, how can I pass in the self argument, as a table, into the function increment?

any help is appreciated

hjpotter92
  • 78,589
  • 36
  • 144
  • 183
dirkwillem
  • 55
  • 2
  • 5
  • 1
    Are you asking how to create a lua table in C++ and pass it to the function? http://stackoverflow.com/questions/453769/how-do-i-create-a-lua-table-in-c-and-pass-it-to-a-lua-function – Ditmar Wendt Jun 26 '12 at 20:30
  • No, I want to pass in a Lua table from my script, as an argument in a lua function, wich i want to call in a C++ function. So actually it is a kind of pointer to the table itselfs – dirkwillem Jun 27 '12 at 15:10

1 Answers1

2

In Lua 5.1 you use lua_getglobal to, um, get a global, like your table a -- you are using it to get your table just a few lines above; all you need to do is duplicate that value to pass it to your function

 lua_getglobal(L, "a"); // the table a is now on the stack
 lua_getfield(L, -1, "increment"); // followed by the value of a.increment

 lua_pushvalue(L,-2); // get the table a as the argument

 lua_pcall(L,1,0,0);
Doug Currie
  • 40,708
  • 1
  • 95
  • 119