作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想返回表(带有键/值对),其中包含从 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/
我是一名优秀的程序员,十分优秀!