views:

520

answers:

2

I have a functions nested relatively deeply in a set of tables. Is there a way in C/C++ to get a "reference" to that function and push that (and args) onto the stack when I need to use it?

+2  A: 

The Lua API (http://www.lua.org/manual/5.1/manual.html#3) can be used to acess any table members you want. Use lua_gettable() to extract a table member and place it on the lua stack, if the member is also a table just call lua_gettable() again to access this table, and so on...

(Depending on what you're doing lua_rawget() might be a better choice than lua_gettable() )

Addtional in response to comment:

Okay that's a bit more interesting. Well, a table is a reference object (more or less), so you'd be probably safe to save the innermost table reference somewhere.

Since the lua API doesn't seem to have anyway to directly manipulate table ref's, you'll probably have to push the ref into a global, or if that doesn't work a new table with a single table entry. When you want the ref later, just get it from the global.

e.g.

// Final table reference is now at top of stack, after multiple dereferences
lua_setglobal( L, "mytableref" );
Andy J Buchanan
I already know how to do that :) I want to get a function referenced nested way deep in tables so that I can later call the function without traversing all those tables.
jameszhao00
[Added to answer]
Andy J Buchanan
+5  A: 

This is what the reference system is for. The function call r = luaL_ref(L, LUA_REGISTRYINDEX) stores the value on the top of the stack in the registry and returns an integer that can be stored on the C side and used to retrieve the value with the function call lua_rawgeti(L, LUA_REGISTRYINDEX, r).

See the PiL chapter, as well as the documentation of luaL_ref(), lua_rawgeti(), and luaL_unref() for the full story.

RBerteig