C++遍历Lua table的方法实例
程序员文章站
2022-04-09 22:49:33
lua table数据如下:
复制代码 代码如下:
--$ cat test.lua lua文件
user = {
&nb...
lua table数据如下:
复制代码 代码如下:
--$ cat test.lua lua文件
user = {
["name"] = "zhangsan",
["age"] = "22",
["friend"] = {
[1] = {
["name"] = "小丽",
["sex"] = "女",
["age"] = "20",
},
[2] = {
["name"] = "小罗",
["sex"] = "男",
["age"] = "20",
},
},
}
要读出上面table 中所有数据,c++代码如下:
复制代码 代码如下:
//c++代码:
#include <lua.hpp>
#include <iostream>
#include <string>
using namespace std;
bool poptable(lua_state* l, int idx)
{
try{
lua_pushnil(l);
while(lua_next(l, idx) != 0){
int keytype = lua_type(l, -2);
if(keytype == lua_tnumber){
double value = lua_tonumber(l, -2);
cout << "key:" << value << endl;
}else if(keytype == lua_tstring){
const char* value = lua_tostring(l, -2);
cout << "key:" << value << endl;
}else{
cout << "invalid key type: " << keytype << endl;
return false;
}
int valuetype = lua_type(l, -1);
switch(valuetype){
case lua_tnil:
{
cout << "value: nil" << endl;
break;
}
case lua_tboolean:
{
int value = lua_toboolean(l, -1);
cout << value << endl;
break;
}
case lua_tnumber:
{ cout << "value:" << lua_tonumber(l, -1) << endl;
break;
}
case lua_tstring:
{
cout << "value:" << lua_tostring(l, -1) << endl;
break;
}
case lua_ttable:
{
cout << "====sub table===" << endl;
int index = lua_gettop(l);
if (!poptable(l, index)) {
cout << "poptable error in poptable,error occured" << endl;
return false;
}
break;
}
default:
{
cout << "invalid value type: " << valuetype << endl;
return false;
}
}
lua_pop(l, 1);
}
}catch(const char* s){
string errmsg = s;
lua_pop(l,1);
cout << errmsg << endl;
return false;
}catch(std::exception& e){
const char* errmsg = e.what();
lua_pop(l,1);
cout << errmsg << endl;
return false;
}catch(...){
const char* errmsg = lua_tostring(l,-1);
lua_pop(l,1);
cout << errmsg << endl;
return false;
}
return true;
}
int main(int argc, char* argv)
{
lua_state* l = lual_newstate();
lual_openlibs(l);
int r = lual_dofile(l,"./test.lua");
lua_getglobal(l, "user");
int type = lua_type(l,1);
if(type == lua_ttable){
int index = lua_gettop(l);
if(poptable(l,index)){
return 0;
}else{
cout << "error" << endl;
return -1;
}
}
return 0;
}
运行结果:
复制代码 代码如下:
$ ./cpptable.linux_64_gcc4
key:age
value:22
key:name
value:zhangsan
key:friend
====sub table===
key:2
====sub table===
key:sex
value:男
key:age
value:20
key:name
value:小罗
key:1
====sub table===
key:sex
value:女
key:age
value:20
key:name
value:小丽