头文件 lua版本 5.1.4
#include <string.h>
extern "C"
{
#include "../lualib/lua.h"
#include "../lualib/lauxlib.h"
#include "../lualib/lualib.h"
};
#ifdef _DEBUG
#pragma comment(lib,"lualib.lib")
#else
#endif
实例代码:
int main (void)
{
char *pbuff ="bgColor = {r=1,g=2,b=3}";
int error;
lua_State *L = lua_open(); /* opens Lua */
luaL_openlibs(L); /* opens the basic library */
error = luaL_loadbuffer(L, pbuff, strlen(pbuff), "line") || lua_pcall(L,0,0,0); ;
if (error){
fprintf(stderr, "%s", lua_tostring(L, -1));
lua_pop(L, 1);/* pop error message from the stack */
}
fprintf(stderr,"现在栈里面一共有多少个原来素: %d\r\n",lua_gettop(L));
lua_getglobal(L,"bgColor"); //此时栈里面压入了这个表。。。
fprintf(stderr,"现在栈里面一共有多少个原来素: %d\r\n",lua_gettop(L));
if (!lua_istable(L,-1))
{
printf("isn't a table\r\n");
}else
{
//这里,压入栈三次,加上上面的一次,就是四次了。。。
lua_pushstring(L,"r");
lua_gettable(L,-2);
lua_pushstring(L,"g");
lua_gettable(L,-3);
lua_pushstring(L,"b");
lua_gettable(L,-4);
fprintf(stderr,"现在栈里面一共有多少个原来素: %d\r\n",lua_gettop(L));
int rvalue = (int) lua_tonumber(L,2); //这里对应的是 -2 ,当然你也可以写成-2,都一样的。
int gvalue = (int) lua_tonumber(L,-3);
int bvalue = (int) lua_tonumber(L,4);
fprintf(stderr,"元素值为 r:%d g:%d b:%d\r\n", rvalue,gvalue,bvalue);
lua_pop(L,4); //清空栈里面的四个元素
fprintf(stderr,"现在栈里面一共有多少个原来素: %d\r\n",lua_gettop(L));
}
lua_close(L);
return 0;
}
运行结果
现在栈里面一共有多少个原来素: 0
现在栈里面一共有多少个原来素: 1
现在栈里面一共有多少个原来素: 4
元素值为 r:1 g:1 b:3
现在栈里面一共有多少个原来素: 0