User Tools

Site Tools


lua:lua

Differences

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

Link to this comparison view

Next revision
Previous revision
lua:lua [2008/09/01 14:36]
deva created
lua:lua [2012/04/20 13:53] (current)
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 = lua_gettop(L);
 +// add '1' to the list
 lua_pushinteger(L, 1); lua_pushinteger(L, 1);
 +lua_rawseti(L, top, 0);
 +// add '2' to the list
 lua_pushinteger(L, 2); lua_pushinteger(L, 2);
 +lua_rawseti(L, top, 1);
 +// add '3' to the list
 lua_pushinteger(L, 3); lua_pushinteger(L, 3);
-lua_rawset(L, -3);+lua_rawseti(L, top, 2); 
 + 
 +// 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, 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.1220272588.txt.gz · Last modified: 2008/09/01 14:36 by deva