Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a table in Lua, then add values from the C API?

Tags:

api

lua

lua-table

Here's what I have so far... It creates global table called "mod", but I can't seem to add indexes to the table...

lua_newtable(L);
lua_setglobal(L,"mod");
like image 407
Sam H Avatar asked Nov 18 '10 23:11

Sam H


1 Answers

The manual says:

void lua_setfield (lua_State *L, int index, const char *k);

Does the equivalent to t[k] = v, where t is the value at the given valid index and v is the value at the top of the stack.

This function pops the value from the stack.

So, more precisely: Push whatever you want to add onto the stack, then call lua_setfield. For example:

lua_pushnumber( L, 42 );
lua_setfield( L, -2, "answer_to_life_universe_and_rest" )

This inserts the field "answer_to_life..." with value 42 into the table.

like image 59
Lagerbaer Avatar answered Oct 17 '22 22:10

Lagerbaer