转https://blog.youkuaiyun.com/u013224233/article/details/87804404?utm_source=app
c调用lua的table
data.lua
print("hello")
width = 10
length = 20
Data =
{
name = "zhang_yi" ,
age = 24 ,
lover = "lijuanxian" ,
}
cpp
#include <iostream>
#include <string.h>
extern "C"{
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
};
using namespace std;
int main(){
//打开lua
lua_State*L=luaL_newstate();
if (!L)
{
cout<<"lua state error\n";
return -1;
}
//打开lua标准库
luaL_openlibs(L);
//执行lua脚本
if(luaL_loadfile(L, "data.lua") || lua_pcall(L, 0,0,0)){
printf("error %s\n", lua_tostring(L,-1));
return -1;
}
//把全局变量 Data表 里的值压入堆栈
lua_getglobal(L,"Data"); //-1
//把指针 s 指向的以零结尾的字符串压栈
lua_pushstring(L, "name"); //name -1 "Data" -2
//此时栈顶为 name
if (lua_isstring(L,-1))
{
const char*p=lua_tostring(L,-1);
cout<<p<<endl;
}
//把 t[k] 值压入堆栈,这里的 t 是指有效索引 index 指向的值,而 k 则是栈顶放的值
//lua_gettable第二个参数是table在栈中的索引,取栈顶作为key,在table中获取相对的value,压入栈(替换掉原来的栈顶key)
lua_gettable(L,-2);
//此时栈顶为name对应的key
if (lua_isstring(L,-1))
{
const char*p=lua_tostring(L,-1);
cout<<p<<endl;
}
printf("lua_gettop=%d\n",lua_gettop(L));
lua_pushstring(L, "age");
printf("lua_gettop=%d\n",lua_gettop(L));
/*printf("lua_gettop=%d\n",lua_gettop(L));
lua_gettable(L,-3);
if (lua_isnumber(L,-1))
{
int nump=lua_tonumber(L,-1);
cout<<nump<<endl;
}*/
lua_pushstring(L, "lover");
printf("lua_gettop=%d\n",lua_gettop(L));
lua_gettable(L,-4);
if (lua_isstring(L,-1))
{
const char*p=lua_tostring(L,-1);
cout<<p<<endl;
}
lua_close(L);
return 0;
}
编译
sudo g++ -I/usr/local/include/ -L/usr/local/lib/ -lm C_use_lua.cpp -o test /usr/local/lib/liblua.a -ldl
gdut17@ubuntu:~/code/python/Project1/Project1$ sudo g++ -I/usr/local/include/ -L/usr/local/lib/ -lm C_use_lua.cpp -o test /usr/local/lib/liblua.a -ldl
gdut17@ubuntu:~/code/python/Project1/Project1$ ./test
hello
name
zhang_yi
lua_gettop=2
lua_gettop=3
lua_gettop=4
lijuanxian