1.一些用来遍历lua表的api简介
以下是对下面几个函数的认识不对请批评指正:
lua_istable:是否是一个表
lua_gettable(L,int index) :把lua栈的索引为index表的lua栈的index+1所指的索引的值弹出。也就是弹出table[index+1]; lua_next(L,index):先把 表(lua栈 index所指的表), 的当前索引弹出,再把table 当前索引的值弹出,也就是先弹出 table的索引,再弹出table索引的值
2.代码示例
// lua_table_extent.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"#include "stdafx.h"#include "lua.hpp"#include "lauxlib.h"#include "lualib.h"#include#include #include using namespace std;#pragma comment(lib,"lua5.1.lib")#pragma comment(lib,"lua51.lib")/*luaJ_table.lua文件内容----------------------------------------------NUMBER_TABLE ={ 11,22,33,44,}NUMBER_TABLE_WITH_INDEX ={["a"] = 1,["b"] = 2,["c"] = 3}STRING_TABLE_WITH_INDEX ={["a"] = "this is a",["b"] = "this is b",["c"] = "this is c"}-----------------------------------------------*/int _tmain(int argc, _TCHAR* argv[]){ lua_State *L = luaL_newstate(); luaL_openlibs(L); if(0 != luaL_loadfile(L,"lua_table.lua")) { printf("loadbuff error :%s",lua_tostring(L,-1)); lua_pop(L,1); } if(0 != lua_pcall(L,0,0,0)) { printf("pcall error :%s",lua_tostring(L,-1)); lua_pop(L,1); } lua_getglobal(L,"STRING_TABLE_WITH_INDEX"); /*此时lua栈状态 ---------------------------------- | -1 table NUMBER_TABLE ---------------------------------- */ if(!lua_istable(L,-1)) cout<<"not a table"<
以上代码的输出为
key:a value:this is akey:c value:this is ckey:b value:this is b请按任意键继续. . .