【发布时间】:2019-01-29 19:33:17
【问题描述】:
我想通过发送一个 C++ 预格式化 Lua 表来改进下面的代码:
int GetCategory(lua_State* L)
{
uint32 Type = CHECKVAL<int>(L, 1);
lua_newtable(L);
int tbl = lua_gettop(L);
uint32 counter = 1;
// Struct CT { string CategoryBrandName, CategoryName }; > Vector<CT>
auto list = sManagerMgr->GetAll();
// Hack modify this to send a metatable/UserData/Table whatever is called
for (auto& elem : list)
{
switch (Type)
{
case 1:
lua_pushstring(L, elem->CategoryBrandName);
break;
case 2:
lua_pushstring(L, elem->CategoryName);
break;
}
lua_rawseti(L, tbl, counter);
counter++;
}
lua_settop(L, tbl);
return 1;
}
基本上, lua_newtable 将表推送到 lua 堆栈, lua_gettop 将采用顶部索引,即表所在的索引。 然后 lua_pushstring(L, ELEMENT); lua_rawseti(L, tbl, 计数器);将 ELEMENT 放到我们使用 gettop 获得的索引 tbl 处的表中。元素的索引是计数器的值。
但是这里的问题是我不得不调用两次函数 GetCategory 来在我的 .lua 文件中填充它。
table.insert(Group, { GetCategory(1), GetCategory(2) });
当前使用:
print(i, Group(1)[i], Group(2)[i]);
所以.. 我宁愿调用一次并直接得到这样的东西:
local Group =
{
[1] = { "elem->CategoryBrandName[1]", "elem->CategoryName[1]" },
[2] = { "elem->CategoryBrandName[2]", "elem->CategoryName[2]" }
--etc
};
我尝试将 elem 填充到 2D Array[1][2] 中,然后推送 Array 失败
我对表格、元表、多维数组等进行了大量研究,但找不到适合我需要或工作的东西。
有人有解决办法吗?
【问题讨论】: