lua 怎么逆序删除table中的元素
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了lua 怎么逆序删除table中的元素相关的知识,希望对你有一定的参考价值。
参考技术A 这三个函数用 Lua 实现分别如下: function PrintLower(str) print(str:lower()) end function MergeAndSort(array1, array2) local array = for _, elem in ipairs(array1) do table.insert(array, elem) end for _, elem in ipairs(array2)本回答被提问者采纳c++ 遍历lua table方法 如图
要读出上面table 中所有数据,答案好加分。。。。。。。。。。。。。急
//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;
--$ cat test.lua lua文件
user =
["name"] = "zhangsan",
["age"] = "22",
["friend"] =
[1] =
["name"] = "小丽",
["sex"] = "女",
["age"] = "20",
,
[2] =
["name"] = "小罗",
["sex"] = "男",
["age"] = "20",
,
,
运行结果:
$ ./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:小丽
参考技术A lua中执行require"base"
cpp中调用lua的函数
prettytostring(user)
就能得到你要的表了
以上是关于lua 怎么逆序删除table中的元素的主要内容,如果未能解决你的问题,请参考以下文章