Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)?

like image 379
GameFreak Avatar asked Feb 08 '10 04:02

GameFreak


People also ask

How do you call C from Lua?

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.

Are tables passed by reference Lua?

Lua's function , table , userdata and thread (coroutine) types are passed by reference. The other types are passed by value.

How do you create a Lua table?

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”.

What is table insert in Lua?

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} .


2 Answers

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
}
like image 110
Kornel Kisielewicz Avatar answered Oct 31 '22 04:10

Kornel Kisielewicz


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;
}
like image 21
mkluwe Avatar answered Oct 31 '22 03:10

mkluwe