C++对Lua中table进行读取、修改和创建

时间:2020-12-22 08:42:26

C++代码:

// LuaAndC.cpp : 定义控制台应用程序的入口点。
// #include "stdafx.h" #include <iostream>
#include <string.h>
using namespace std; extern "C"
{
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
} int _tmain(int argc, _TCHAR* argv[])
{
//1.创建一个state
lua_State *L = luaL_newstate(); luaL_openlibs(L);
luaL_dofile(L,"Hello.lua"); //获取table的值
lua_getglobal(L,"str"); //会将get的对应项压到栈顶
lua_getfield(L,1,"name");
lua_getfield(L,1,"age"); if(lua_isstring(L,2))
{
cout<<"name= "<<lua_tostring(L,-2)<<endl;
}
if(lua_isnumber(L,3))
{
cout<<"age= "<<lua_tonumber(L,-1)<<endl;
}
lua_pop(L,2); //修改table的项
lua_pushfstring(L,"So so");//改完弹出
lua_setfield(L,1,"name");
lua_getfield(L,1,"name");
if(lua_isstring(L,2))
{
cout<<"name1= "<<lua_tostring(L,2)<<endl;
}
lua_pop(L,2); //新建table
lua_newtable(L); //压栈
lua_pushnumber(L,11);
lua_pushstring(L,"New");
lua_setfield(L,1,"name");
lua_setfield(L,1,"age");
lua_getfield(L,1,"name");
lua_getfield(L,1,"age");
if(lua_isstring(L,2))
{
cout<<"name= "<<lua_tostring(L,2)<<endl;
}
if(lua_isnumber(L,3))
{
cout<<"age= "<<lua_tonumber(L,3)<<endl;
} lua_pop(L,3); //关闭state
lua_close(L); int i;
cin>>i;
return 0 ;
}

Lua代码:

str={name="Hunter",age=18}