PDA

View Full Version : Accessing Lua tables in C/C++


Dig
10-29-2005, 05:38 AM
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

Reedbeta
10-29-2005, 01:10 PM
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.

Dig
10-30-2005, 01:29 AM
That works great, thanks, might be right out of the manual, but your version is easier to understand!

cheers,
Nick