User Tools

Site Tools


lua:lua

This is an old revision of the document!


LUA

C/C++

Arrays

myarray = {1,2,3};

corresponds to

lua_createtable(L, 0, 3);
int top = lua_gettop(L);
// add '1' to the list
lua_pushinteger(L, 1);
lua_rawseti(L, top, 0);
// add '2' to the list
lua_pushinteger(L, 2);
lua_rawseti(L, top, 1);
// add '3' to the list
lua_pushinteger(L, 3);
lua_rawseti(L, top, 2);
 
// and then some code to bind it to "myarray"

Fields (maps)

foo = {}
foo.hello = 'world'
foo.bar = {}
foo.bar.ping = 'pong'
foo.bar.bas = {}
foo.bar.bas.ding = 'ring'

Corresponds to:

int foo, bar, bas;
 
// Create global 'foo'
lua_newtable(L);
lua_setglobal(L, "foo");
 
// Set foo.hello = 'world'
lua_getglobal(L, "foo");
foo = lua_gettop(L);
lua_pushstring(L, "world");
lua_setfield(L, foo, "hello");
 
// Create 'bar' in 'foo'
lua_getglobal(L, "foo");
foo = lua_gettop(L);
lua_newtable(L);
lua_setfield(L, foo, "bar");
 
// Set foo.bar.ping = 'pong'
lua_getglobal(L, "foo");
foo = lua_gettop(L);
lua_getfield(L, foo, "bar");
bar = lua_gettop(L);
lua_pushstring(L, "pong");
lua_setfield(L, bar, "ping");
 
// Create 'bas' in 'foo.bar'
lua_getglobal(L, "foo");
foo = lua_gettop(L);
lua_getfield(L, foo, "bar");
bar = lua_gettop(L);
lua_newtable(L);
lua_setfield(L, bar, "bas");
 
// Set foo.bar.bas.ding = 'ring'
lua_getglobal(L, "foo");
foo = lua_gettop(L);
lua_getfield(L, foo, "bar");
bar = lua_gettop(L);
lua_getfield(L, bar, "bas");
bas = lua_gettop(L);
lua_pushstring(L, "ding");
lua_setfield(L, bas, "ring");
 
lua_pop(L, 1); // pop 'foo' off the stack.
lua/lua.1309424233.txt.gz · Last modified: 2011/06/30 10:57 by deva