方式一:
访问key为数字的table
extern "C"{
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
};
#pragma comment(lib,"lua5.1.lib")
int main()
{
lua_State* L = luaL_newstate();
if (luaL_loadstring(L,"back= { 0.30, 0.10, 0 }")
|| lua_pcall(L,0,0,0)) {
printf("Error Msg is %s.\n",lua_tostring(L,-1));
return -1;
}
// if (luaL_dofile(L,"test.lua")) {
// printf("Error Msg is %s.\n",lua_tostring(L,-1));
// return -1;
// }
lua_getglobal(L,"back");
if (!lua_istable(L,-1)) {
printf("'background' is not a table.\n" );
return -1;
}
int size=lua_objlen(L,-1);
for (int i=1;i<=size;i++)
{
lua_pushnumber(L,i);
lua_gettable(L,-2);
printf("%f\n",lua_tonumber(L,-1));
lua_pop(L,1);
}
lua_close(L);
return 0;
}
方式二:
访问key为字符串等任意的table
extern "C"{
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
};
#pragma comment(lib,"lua5.1.lib")
int main()
{
lua_State* L = luaL_newstate();
if (luaL_loadstring(L,"back= { r=0.30, g=0.10, b=0 }")
|| lua_pcall(L,0,0,0)) {
printf("Error Msg is %s.\n",lua_tostring(L,-1));
return -1;
}
// if (luaL_dofile(L,"test.lua")) {
// printf("Error Msg is %s.\n",lua_tostring(L,-1));
// return -1;
// }
lua_getglobal(L,"back");
if (!lua_istable(L,-1)) {
printf("'background' is not a table.\n" );
return -1;
}
// int size=lua_objlen(L,-1);
// for (int i=1;i<=size;i++)
// {
// lua_pushnumber(L,i);
// lua_gettable(L,-2);
// printf("%f\n",lua_tonumber(L,-1));
// lua_pop(L,1);
// }
lua_pushnil(L);
while (lua_next(L,-2))
{
printf("%f\n",lua_tonumber(L,-1));
lua_pop(L,1);
}
lua_close(L);
return 0;
}
方式三:http://blog.csdn.net/huangjm_13/article/details/8194201
C/C++听过key(键)或index(索引)来访问和修改Lua中的Table的内容
WriteLuaTable.lua
luat_Test1={a=123, b=456, c=789} luat_Test2={123, 456, 789} |
#include <lua.hpp> |