Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pushing a Lua table

I have created a Lua table in C, but I'm not sure how to push that table onto the top of a stack so I can pass it to a Lua function.

Does anyone know how to do this?

This is my current code:

lua_createtable(state, libraries.size(), 0);
int table_index = lua_gettop(state);
for (int i = 0; i < libraries.size(); i++)
{
    lua_pushstring(state, libraries[i].c_str());
    lua_rawseti(state, table_index, i + 1);
}

lua_settable(state, -3);

[ Push other things ]
[ Call function ]
like image 901
Tom Leese Avatar asked Oct 21 '10 13:10

Tom Leese


People also ask

How do I insert a table into Lua?

In Lua, the table library provides functions to insert elements into the table. The insert function usually takes two arguments, the first argument is usually the name of the table from which we want to insert the element to, and the second argument is the element that we want to insert.

How does a table work in Lua?

Tables are the only data structure available in Lua that helps us create different types like arrays and dictionaries. Lua uses associative arrays and which can be indexed with not only numbers but also with strings except nil. Tables have no fixed size and can grow based on our need.

How do I remove a table from Lua?

remove () function. The table. remove () function removes a value from an array using the index position of the value to be removed. This function removes the element at the pos position from the table.


1 Answers

Here's a quick helper function to push strings to the table

void l_pushtablestring(lua_State* L , char* key , char* value) {
    lua_pushstring(L, key);
    lua_pushstring(L, value);
    lua_settable(L, -3);
} 

Here I use the helper function to create the table and pass it to a function

// create a lua function
luaL_loadstring(L, "function fullName(t) print(t.fname,t.lname) end");
lua_pcall(L, 0, 0, 0);

// push the function to the stack
lua_getglobal(L, "fullName");

// create a table in c (it will be at the top of the stack)
lua_newtable(L);
l_pushtablestring(L, "fname", "john");
l_pushtablestring(L, "lname", "stewart");

// call the function with one argument
lua_pcall(L, 1, 0, 0);
like image 100
Nick Van Brunt Avatar answered Sep 22 '22 06:09

Nick Van Brunt