/*1.lua*/
luat_Test1={a=123, b=456, c=789}
luat_Test2={123, 456, 789}
luatable = {
{
Level = 1,sid = "monster"
},
{
Level = 2,sid = "man"
}
}
for i,v in pairs(luatable)do
for j,v1 in pairs(v)do
print(j,v1);
end;
end;
#include <lua.hpp>
#include<iostream>
using namespace std;
static void ReadTableFromItem(lua_State *L, const char* lpszTableName, const char* lpszTableItem)
{
//获取lua中的lpszTableName Table的值 ,并压入栈
lua_getglobal(L, lpszTableName);
//把字符串压入栈顶
lua_pushstring(L, lpszTableItem);
<span style="font-size:12px;"><span style="font-family:SimSun;">//lua_getta</span><span style="font-family:SimSun;">ble以table在栈</span><span style="font-family:SimSun;">中的索引作为参数,弹出栈顶的元素作为key,返回与key对应的value并压入栈顶。</span></span>
<span style="font-family: SimSun;font-size:12px;">//</span><span style="font-family: SimSun;font-size:12px;">lua_gettable会弹出栈顶的key,然后把对应的value压入</span>
lua_gettable(L, -2);
printf("%s.%s=%d\n", lpszTableName, lpszTableItem, (int)lua_tonumber(L, -1));
//弹出两个数据
lua_pop(L,2);
}
static void ReadTableFromIndex(lua_State *L, const char* lpszTableName, int index)
{
lua_getglobal(L, lpszTableName);
//取得table[index]并放到栈顶
lua_rawgeti(L, -1, index);
printf("%s[%d]=%d\n", lpszTableName, index, (int)lua_tonumber(L, -1));
lua_pop(L, 2);
}
static void EnumTableItem(lua_State *L, const char* lpszTableName)
{
lua_getglobal(L, lpszTableName);
int it = lua_gettop(L);//取得栈顶元素的索引,即栈中元素的个数
lua_pushnil(L);//压入nil到栈里
printf("Enum %s:", lpszTableName);
/*
lua_next() 这个函数的工作过程是:
1) 先从栈顶弹出一个 key
2) 从栈指定位置的 table 里取下一对 key-value,先将 key 入栈再将 value 入栈
3) 如果第 2 步成功则返回非 0 值,否则返回 0,并且不向栈中压入任何值
*/
while(lua_next(L, it))
{
printf(" %d", (int)lua_tonumber(L, -1));
lua_pop(L, 1);
}
printf("\n");
lua_pop(L, 1);
}
int main (int argc, char* argv[])
{
lua_State *L = luaL_newstate();
luaopen_base(L);
luaL_dofile(L, "2.lua");
ReadTableFromItem(L, "luat_Test1", "a"); // 等价与lua代码:print(luat_Test1.a)
ReadTableFromItem(L, "luat_Test1", "b");
ReadTableFromItem(L, "luat_Test1", "c");
EnumTableItem(L, "luat_Test1"); // 枚举Table
ReadTableFromIndex(L, "luat_Test2", 1); // 等价与lua代码:print(luat_Test1[1])
ReadTableFromIndex(L, "luat_Test2", 2);
ReadTableFromIndex(L, "luat_Test2", 3);
EnumTableItem(L, "luat_Test2");
lua_close(L);
getchar();
return 0;
}