GameFreak GameFreak - 1 month ago 6
C++ Question

How to I pass a table from Lua into C++?

How would I pass a table of unknown length from Lua into a bound C++ function?

I want to be able to call the Lua function like this:

call_C_Func({1,1,2,3,5,8,13,21})


And copy the table contents into an array (preferably STL vector)?

Answer

If you use LuaBind it's as simple as one registered call. As for rolling up your own, you need to take a look at lua_next function.

Basically the code is as follows:

lua_pushnil(state); // first key
index = lua_gettop(state);
while ( lua_next(state,index) ) { // traverse keys
  something = lua_tosomething(state,-1); // tonumber for example
  results.push_back(something);
  lua_pop(state,1); // stack restore
}