How to push a Lua table as an argument?


We may want to push the Lua table as an argument to a code written in C++ which uses Lua as an embedded language and for that case we need to make use of the different API functions that the Lua library provides us with.

Example

The Lua code will look something like the code shown below −

a = {
   numb = 10,
   create = function(a)
      print(a);
   end,
increment = function(self)
   --self.numb = 11;
   print(self.numb);
end,
decrement = function(self,i)
   self.numb = self.numb-i;
   print(self.numb);
end
};
b = a;

And the C++ code that will invoke the Lua functions will look like this −

luaL_openlibs(L);
luaL_dofile (L,"main.lua");
lua_getglobal(L, "a");
lua_getfield(L, -1, "increment");
lua_pushvalue(L,-2); // get the table a as the argument
lua_pcall(L ,1,0,0);
printf(" 
I am done with Lua in C++.
"); lua_close(L);

In the above code, the call to lua_pushvalue(L,-2) is the one that does the magic, as it enables us to pass the table a as the argument.

Output

11
I am done with Lua in C++

Updated on: 19-Jul-2021

466 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements