Accessing Lua tables in C/C++

501a71cbc1147ecae8bdcba9d2b35b71
0
Dig 101 Oct 29, 2005 at 11:38

I’m working on a basic scripted (Lua 5.0) ‘game’ engine, and part of the concept is that you define an object by creating a table that has information suchs as x,y,z value, size, object type etc., and the pass it to my C++ engine to create the object. I have no problem using objects in C++ and Lua through Lunar class template and can have me engine do all sort of things with the variable passed but can’t work out how to make my C++ functions accept a TABLE from Lua and set internal variable based on the values in that table.

Hope that makes a little bit of sense and someone can point me in the right direction to working this out! Can’t find any tutorials on this (found ones that recognise a table was passed, but not ones that process the information in the table) and the Lua Manual makes no sense to me.

Cheers,
Nick
www.littlemonkey.co.nz

2 Replies

Please log in or register to post a reply.

A8433b04cb41dd57113740b779f61acb
0
Reedbeta 167 Oct 29, 2005 at 19:10

When your Lua function calls a C function, the parameters will be passed on the stack. I assume you know the stack index (“idx”) of the table you wish to manipulate.

To get the member “size” of the table

lua_pushstring(L, "size");
lua_gettable(L, idx);   // This pops "size", gets the value of "size" in the table and pushes the value
int size = lua_tonumber(L, -1);   // Get the returned value off the stack
lua_pop(L, 1);   // Pops that value off the stack (returning stack to its original state)

To set the member “size” of the table to 256

lua_pushstring(L, "size");
lua_pushnumber(256);
lua_settable(L, idx);  // This pops the "size" and the 256, and sets "size" to 256 in the table

This is right out of the manual, section 3.11.

501a71cbc1147ecae8bdcba9d2b35b71
0
Dig 101 Oct 30, 2005 at 08:29

That works great, thanks, might be right out of the manual, but your version is easier to understand!

cheers,
Nick