初步想法利用luaExpat, 但是expat不友好支持DOM parser只支持SAX,所以转向xmlLib2.
Lua nested table iteration:
lua:
tbl1 = {
{ a = "aa",b = "bb", c = "cc"},
{ d= "dd", e = "ee", f = "ff"},
}
tbl2 = {
{ aa = "aaa",bb = "bbb", cc = "ccc", gg = { g1 = "g1g1",g2 = "g2g2"},},
{ dd = "ddd", ee = "eee", ff = "fff"},
}
C: code snippet:
lua_pushstring(L, "hello world1");
lua_pushstring(L, "hello world12");
lua_pushstring(L, "hello world123");
Lua_pushvalue(L, 1);
Lua_getglobal(L, "tbl1");
t1 = lua_gettop(L);
lua_getglobal(L, "tbl2");
T2 = lua_gettop(L);
table_dump(L, t1, 3)
table_dump(L, t2, 3);
- int lua_next (lua_State *L, int index); index, 表不需要在栈顶
- 多重表格的遍历: lua_next是 先弹出1个元素,压入2个元素key-value, lua_pushnil仅仅是为了配合这- pop(1) push(2), pop(1) 操作而做的“无用操作”.
- 多重表格,碰到子表时,先是子表本身的key,值value是 table, 然后再说lua_next子表的内部元素。
- 循环时注意栈的平衡
/* Print a Lua table. depth_limit is the limit on recursive printing of
subtables. */
static void table_dump (lua_State *L, int idx, int depth_limit)
{
idx = lua_absindex(L, idx);
assert(lua_type(L, idx) == LUA_TTABLE);
printf("{");
for (lua_pushnil(L);; /*lua_next(L, idx); lua_pop(L, 1)*/) //分开为了调试,利用lua_gettop(L)查看栈长度,需要刷新
{
if ( lua_next(L, idx) <=0 ) break;
value_dump(L, -2, depth_limit - 1);
printf(" = ");
value_dump(L, -1, depth_limit - 1);
printf(", ");
lua_pop(L, 1);
}
printf("}");
}
/* Print a Lua value. depth_limit controls the depth to which tables will be
printed recursively (0 for no recursion). */
void value_dump (lua_State *L, int idx, int depth_limit)
{
int t ;
idx = lua_absindex(L, idx);
t = lua_type(L, idx);
switch (t)
{
case LUA_TSTRING: /* strings */
printf("'%s'", lua_tostring(L, idx));
break;
case LUA_TBOOLEAN: /* booleans */
printf(lua_toboolean(L, idx) ? "true" : "false");
break;
case LUA_TNUMBER: /* numbers */
printf("%g", lua_tonumber(L, idx));
break;
case LUA_TTABLE:
if (depth_limit > 0)
table_dump(L, idx, depth_limit);
else
printf("table: %p", lua_topointer(L, idx));
break;
case LUA_TTHREAD:
case LUA_TFUNCTION:
case LUA_TUSERDATA:
case LUA_TLIGHTUSERDATA:
printf("%s: %p", lua_typename(L, t), lua_topointer(L, idx));
break;
default: /* other values */
printf("%s", lua_typename(L, t));
break;
}
}
请发表评论