User Tools

Site Tools


lua:lua

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
Last revisionBoth sides next revision
lua:lua [2008/09/01 15:41] devalua:lua [2012/04/20 11:57] deva
Line 1: Line 1:
 =====LUA===== =====LUA=====
-====c/c++====+====C/C++==== 
 +===Arrays===
 <code lua> <code lua>
 myarray = {1,2,3}; myarray = {1,2,3};
Line 8: Line 9:
 <code c> <code c>
 lua_createtable(L, 0, 3); lua_createtable(L, 0, 3);
-int top = gettop(L);+int top = lua_gettop(L);
 // add '1' to the list // add '1' to the list
 lua_pushinteger(L, 1); lua_pushinteger(L, 1);
Line 20: Line 21:
  
 // and then some code to bind it to "myarray" // and then some code to bind it to "myarray"
 +</code>
 +
 +===Array of arrays===
 +An array with 10 entries each containing 2 entries:
 +<code>
 +  int num = 10;
 +  int sz = 2;
 +  
 +  lua_createtable(L, num * sz, 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;
 +</code>
 +
 +===Fields (maps)===
 +<code lua>
 +foo = {}
 +foo.hello = 'world'
 +foo.bar = {}
 +foo.bar.ping = 'pong'
 +foo.bar.bas = {}
 +foo.bar.bas.ding = 'ring'
 +</code>
 +
 +Corresponds to:
 +<code c>
 +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.
 </code> </code>
lua/lua.txt · Last modified: 2012/04/20 13:53 by deva