Jump to content


Accessing Lua tables in C/C++


2 replies to this topic

#1 Dig

    New Member

  • Members
  • Pip
  • 2 posts

Posted 29 October 2005 - 11: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

#2 Reedbeta

    DevMaster Staff

  • Administrators
  • 5307 posts
  • LocationBellevue, WA

Posted 29 October 2005 - 07: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.
reedbeta.com - developer blog, OpenGL demos, and other projects

#3 Dig

    New Member

  • Members
  • Pip
  • 2 posts

Posted 30 October 2005 - 08:29 AM

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

cheers,
Nick





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users