gpt4 book ai didi

c++ - 如何从 C++ 创建表(带有键/值对)并将其推送到 lua?

转载 作者:行者123 更新时间:2023-11-30 03:44:23 24 4
gpt4 key购买 nike

我想返回表(带有键/值对),其中包含从 C++ 函数到 lua 的函数。在 lua 端,函数的返回值是表。但是, table 是空的。

我尝试了字符串而不是函数,但它也没有用。

如果我使用索引而不是键,它就可以工作。但我想放一个键,而不是索引。

lua_newtable(L);
for(list<NativeFunction_t>::iterator it = nativeFuncs.begin(); it != nativeFuncs.end(); it++)
{
NativeFunction_t tmp = *it;
cout << "Loading " << tmp.Name << " to lua...";
lua_pushstring(L, tmp.Name);
//If I do lua_pushstring(L, (Index)) instead of above, it works.
//lua_pushstring(L, tmp.Name);
lua_pushcfunction(L, tmp.Func);
lua_settable(L, -3);
cout << "Success" << endl;
}
//lua_setglobal(L, loadAs);
cout << "Done" << endl;
return 1;

我创建和返回表的方式有问题吗?

这里是lua代码。

print("Loading NativeLoader...")
NativeLoader = require("Module")
print("Loading library...")
NativeLoader.Load("Hello", "TestLibrary")
print("Looking library...")
print("TestLibrary: " ..#TestLibrary)
for n, item in ipairs(TestLibrary) do
print(item)
end
--t.hello()
--t.bye()

最佳答案

看起来您正在表中使用字符串键。

ipairs 只遍历从 1 到 n 的整数键。正如 siffejoe 在评论中所建议的那样,您应该改用 pairs 。但是,您应该注意 pairs 不会按照元素插入表中的顺序循环遍历元素。

如果您需要元素按特定顺序排列,您可能希望返回一个额外的表,其中包含按特定顺序排列的字符串键。或者,您可能希望将返回的原始表制作成一个数组,该数组包含在不同表键处包含名称和函数的表。

另请注意,长度运算符仅适用于整数键序列。因此,对于仅使用字符串键的表,它将始终返回 0。

我建议您通读 lua 引用手册中的长度运算符、pairs 和 ipairs。以下是 lua 5.3 手册的链接:

关于c++ - 如何从 C++ 创建表(带有键/值对)并将其推送到 lua?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35520459/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com