LUA-c++交互篇-c++向lua传递table

1.代码

1.1 如果你只想传递一个table

// An highlighted block
typedef unordered_map<string, double> sdmap;
static void addDic(lua_State* L, sdmap& mp) {

	sdmap::iterator it = mp.begin();
	lua_newtable(L);//创建一个表格,放在栈顶
	while (it != mp.end()) {
		string data = it->first;
		lua_pushstring(L,data.c_str());//压入key
		lua_pushnumber(L, it->second);//压入value
		lua_settable(L, -3);//弹出key,value,并设置到table里面去
		it++;
	}
}

1.2 如果你想要传递很多table

static int addTableArray(lua_State *L_,int size,sdmap* map)
{
	lua_newtable(L_); 
	int i = 1; 
	 
	for (int i = 1; i < size;i++)
	{
		lua_pushnumber(L_, i);
		lua_newtable(L_);

		sdmap::iterator it = map[i-1].begin();
		while (it != map[i - 1].end()) {
			lua_pushstring(L_, it->first.c_str());
			lua_pushnumber(L_, it->second);
			lua_settable(L_, -3);
			it++;
		}
		lua_settable(L_, -3);
	}
	delete[] map;
	return 1;
}

下图是在c++中调用这个接口的例子:
注意,在extern “C”的代码中,返回的是1,也就是栈底
如果你对栈的位置由问题,建议参考游戏服务器开发大纲里面关于lua的东西

在这里插入图片描述

2. 测试

2.1 c++代码段

	double x, y, z;
	sdmap mp;
	mp.insert({ "x",x });
	mp.insert({ "y",y });
	mp.insert({ "z",z });
	addDic(L, mp);
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值