lua表操作

头文件 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




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值