All the examples I found that handled tables on the C++ side used the "newtable" method. This creates a table on the stack, which I can refer to, but I don't seem to be able to extract it so that it will remain between calls.
I'll just answer this. From the
Lua 5.1 Reference Manual:
| Lua provides a registry, a pre-defined table that can be used by any C code to store whatever Lua value it needs to store. This table is always located at pseudo-index LUA_REGISTRYINDEX. Any C library can store data into this table, but it should take care to choose keys different from those used by other libraries, to avoid collisions. Typically, you should use as key a string containing your library name or a light userdata with the address of a C object in your code. |
So if you've got a table you want to hang on to at the top of the stack (of some
lua_State *L), just say:
lua_setfield(L, LUA_REGISTRYINDEX, "jebHarvestLib.superSpecialTable");
This'll pop the table from the stack. To get that table back later, say:
lua_getfield(L, LUA_REGISTRYINDEX, "jebHarvestLib.superSpecialTable");
and hey! it's back on top of the stack again. Do note that you shouldn't use integers as keys in the registry. These are reserved for the reference system: instead of making up long string keys and hoping for no conflicts with whatever other C libraries might be putting in the registry, just say:
int specialRef = luaL_ref(L, LUA_REGISTRYINDEX);
This pops whatever is on top of L's stack and stores in the registry under a unique integer key. The return value is that key, so save it somewhere. When you want the table (or whatever you stored) back, just say:
lua_rawgeti(L, LUA_REGISTRYINDEX, specialRef);
When you're done with whatever you saved, you can turn the key back over to the reference system by saying:
luaL_unref(L, LUA_REGISTRYINDEX, specialRef);
As for fitting this into your larger design: because your Lua scripts play with object data so much, why not let each C++ object store all its data (or all its game-logic data) in a Lua table? In the constructor, call
lua_newtable(lua_State*), then put the table in the registry and only save the key on the C++ side.
(Just one option, of course. I didn't follow your explanation too well, so maybe you wanted something else?)