User Tools

Site Tools


lua:lua

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"

Array of arrays

An array with 10 entries each containing 2 entries:

  int num = 10;
  int sz = 2;
  
  lua_createtable(L, num, 0);
  int toptop = lua_gettop(L);

  for(int i = 1; i <= num; i++) {
    lua_createtable(L, 0, sz);
    int top = lua_gettop(L);

    for(int j = 1; j <= sz; j++) {
      char buf[10];
      sprintf(buf, "%d-%d", i, j);
      lua_pushstring(L, buf);
      lua_rawseti(L, top, j);
    }

    lua_rawseti(L, toptop, i);
  }

  return 1;

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.txt · Last modified: 2012/04/20 13:53 by deva