// lua_table_extent.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include "stdafx.h"
#include "lua.hpp"
#include "lauxlib.h"
#include "lualib.h"
#include <string.h>
#include <windows.h>
#include <iostream>
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"<<endl;
/*此时lua栈状态
----------------------------------
| -1 table NUMBER_TABLE
----------------------------------
*/
lua_pushnumber(L,1);
/*此时lua栈状态
----------------------------------
| -1 1 key
| -2 table NUMBER_TABLE
----------------------------------
*/
lua_gettable(L,-2);
/*此时lua栈状态
----------------------------------
| -1 1 Value
| -2 table NUMBER_TABLE
----------------------------------
*/
if(lua_isnumber(L,-1))
cout<<lua_tonumber(L,-1)<<endl;
else if(lua_isstring(L,-1))
cout<<lua_tostring(L,-1)<<endl;
/*此时lua栈状态
----------------------------------
| -1 1 Value
| -2 table NUMBER_TABLE
----------------------------------
*/
lua_pop(L,1);
/*此时lua栈状态
----------------------------------
| -1 table NUMBER_TABLE
----------------------------------
*/
//循环遍历
lua_pushnil(L);
/*此时lua栈状态
----------------------------------
| -1 nil
| -2 table NUMBER_TABLE
----------------------------------
*/
while(lua_next(L,-2))
{
/*此时lua栈状态
----------------------------------
| -1 value
| -2 key
| -3 table NUMBER_TABLE
----------------------------------
*/
if(lua_isnumber(L,-2))
cout<<"key:"<<lua_tonumber(L,-2)<<'\t';
else if(lua_isstring(L,-2))
cout<<"key:"<<lua_tostring(L,-2)<<'\t';
if(lua_isnumber(L,-1))
cout<<"value:"<<lua_tonumber(L,-1)<<endl;
else if(lua_isstring(L,-1))
cout<<"value:"<<lua_tostring(L,-1)<<endl;
/*此时lua栈状态
----------------------------------
| -1 value
| -2 key
| -3 table NUMBER_TABLE
----------------------------------
*/
lua_pop(L,1);
/*此时lua栈状态
----------------------------------
| -1 key
| -2 table NUMBER_TABLE
----------------------------------
*/
}
lua_pop(L,1);
/*此时lua栈状态
----------------------------------
| -1 table NUMBER_TABLE
----------------------------------
*/
lua_close(L);
system("pause");
return 0;
}
key:a value:this is a
key:c value:this is c
key:b value:this is b
请按任意键继续. . .