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)?
Moreover, for a C function to be called from Lua, we must register it, that is, we must give its address to Lua in an appropriate way. When Lua calls a C function, it uses the same kind of stack that C uses to call Lua. The C function gets its arguments from the stack and pushes the results on the stack.
Lua's function , table , userdata and thread (coroutine) types are passed by reference. The other types are passed by value.
In Lua the table is created by {} as table = {}, which create an empty table or with elements to create non-empty table. After creating a table an element can be add as key-value pair as table1[key]= “value”.
The table.insert function inserts an element in a given position of an array, moving up other elements to open space. Moreover, insert increments the size of the array (using setn ). For instance, if a is the array {10, 20, 30} , after the call table.insert(a, 1, 15) a will be {15, 10, 20, 30} .
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
}
This would be my attempt (without error checking):
int lua_test( lua_State *L ) {
std::vector< int > v;
const int len = lua_objlen( L, -1 );
for ( int i = 1; i <= len; ++i ) {
lua_pushinteger( L, i );
lua_gettable( L, -2 );
v.push_back( lua_tointeger( L, -1 ) );
lua_pop( L, 1 );
}
for ( int i = 0; i < len; ++i ) {
std::cout << v[ i ] << std::endl;
}
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With