您的位置:首页 > 编程语言 > Lua

lua中table中嵌套table的使用

2013-04-25 17:36 232 查看
arr={11,22,33, x={m=10, n=20}, y= {p=33, q=44, t={o=99, w={nx=200}}}, t= {xy=10}}

/*这里说明在for循环体内是不能使用操作符 “.” 来访问表中的表的*/
function test(tblName)
for i, v in pairs(tblName)
do
print(i, v, type(i), type(tblName.i), type(tblName[i]))
end
end

/*这里说明在不使用for等循环体内使用table中的表时,可以使用操作符“.”来完成,或者使用操作符“[]”而且必须嵌套的表明使用 双引号*/
print(type(arr.x), type(arr[x]), type(arr["x"]));
test(arr);


#include <stdio.h>
#include <string.h>

#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"

/**  file description:
*
*		使用luaL_dostring去加载字符串(首先使用luaL_loadstring加载函数,然后调用lua_Pcall才能加载到状态机中)和单独调用luaL_loadstring不同
*
*/

//这个东西定义成全局是方便之后其他函数不需要在传递,that's all
lua_State* L;

#define funcStr "backup={1,2,3, x={a=20, b=40}}"

void showStack(lua_State *L, char *pNote)
{
int top = lua_gettop(L);
printf("------------------- %s [%d]-----------------\n", pNote, top);

for (int i = top; i >= 1; i--)
{
printf("[%d] -> ", i);

int t = lua_type(L,i);
switch(t)
{
case LUA_TSTRING:
printf("'%s' \n",lua_tostring(L,i));
break;
case LUA_TBOOLEAN:
printf(lua_toboolean(L,i) ? "true\n" : "false\n");
break;
case LUA_TNUMBER:
printf("%g\n",lua_tonumber(L,i));
break;
case LUA_TFUNCTION:
printf("function here\n");
break;
case LUA_TTABLE:
printf("table here\n");
break;
default:
printf("%s\n",lua_typename(L,t));
break;
}
}
}

#define init(a) memset(a, 0, sizeof((a)))

int main()
{
int ret =0;
char buff[1100] ={0};

L = luaL_newstate();
L = lua_open();
luaL_openlibs(L);

/*dostring*/
ret = luaL_loadstring(L, funcStr) || lua_pcall(L, 0, 0, 0);
showStack(L, "doString");

lua_getglobal(L, "backup");
showStack(L, "backup");
lua_getfield(L, -1, "x");
showStack(L, "backup");
lua_getfield(L, -1, "a");
lua_getfield(L, -2, "b");
showStack(L, "table x");

/*WHY: 直接操作全局的表,往里面添加新数据*/
showStack(L, "prev add y");
sprintf(buff, "backup.y = {a=11, b=22}");
luaL_dostring(L, buff);
lua_pop(L, 3);
lua_getfield(L, -1, "y");
showStack(L, "add y");

init(buff);
strcpy(buff, "a=10");
luaL_dostring(L, buff);
init(buff);
strcpy(buff,"print(a)");
luaL_dostring(L, buff);
showStack(L, "test a");

char buff2[5000] = {0};
/*sprintf(buff, "function printf() table.foreach(backup, function(i, v) print (i, v) end)  end");*/

sprintf(buff2, " function printf(tblName) "
" print (tblName)"
//" lua_getglobal(L, %s) "
" for i, v in pairs(%s) "
" do "
" print (i, v, type(%s[i]), type(table))"
" if type(%s[i])== type(table) then printf(%s[i])  end"
" end "
" end ",  "backup","backup", "backup", "backup");
buff2[strlen(buff2)] ='\0';

luaL_dostring(L, buff2);
lua_getglobal(L, "printf");
lua_pushstring(L, "backup");
lua_pcall(L, 1,0,0);
showStack(L, "printf");

lua_close(L);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: