从元表字段/方法访问数组索引
Array index access from metatable field/method
我有一些反映一些c++类/结构的元表。我通常依靠__index来调用对象的任何字段/方法,并在一个函数中解析它们。
我遇到的困难是当我想传递参数到一个字段,像这样:
anim = playerInfo.animations
while anim do
print (anim)
numstates = anim.numstates
for i = 1, numstates do
state = anim.states(i) <--- This line right here is the issue
print(state)
end
anim = anim.next
end
下面是相关的C代码:
static const struct luaL_Reg objanimationlib_m[] = {
{"__tostring", objanimation2string},
{"__index", objanimationget},
{"__newindex", objanimationset},
{NULL, NULL}
};
luaL_newmetatable(L, "objanimation");
lua_pushvalue(L, -1); // duplicates the metatable
luaL_setfuncs(L, objanimationlib_m, 0);
__index函数内部:
else if (!strcmp(field, "states"))
{
int number = (int)luaL_checknumber(L, 3) - 1; // -1 cuz Lua is not 0-based
if (number >= anim->numstates)
return 0;
PushUserdata(&anim->states[number], "objstate");
}
运行脚本,我得到一个错误:
Warning: [string "test.lua"]:13: bad argument #3 to '__index' (number expected, got no value)
我觉得我错过了一些愚蠢的简单的东西。这是什么?编辑:这是我的解决方案,内部__index函数:
else if (!strcmp(field, "states"))
{
lua_newtable(L);
int i;
for (i = 0; i < anim->numstates; i++)
{
PushUserdata(&anim->states[i], "objstate");
lua_rawseti(L, -2, i+1);
}
}
返回一个充满userdata元素的表。可能会很昂贵,所以这也会提高性能:
anim = playerInfo.animations
while anim do
print (anim)
numstates = anim.numstates
states = anim.states
for i = 1, numstates do
print(states[i])
end
anim = anim.next
end
state = anim.states(i)
等价于
do local f=anim.states; state=f(i) end
所以你的元方法永远不会看到i
换句话说,index元方法接收两个参数,表和键。它返回的内容不一定服从于任何元方法,除非您显式地这样做。
我去定义__len
返回numstates
和__call
处理anim.states(i)
,这样你的代码可以写
for i = 1, #anim do
state = anim(i)
print(state)
end
相关文章:
- 在 C++ 中访问数组负索引处的内存不会返回垃圾
- 使用指针访问数组中的对象数据成员
- VTK 图像数据,访问数组中的 1 个图像
- 调用函数后无法访问数组
- 如何从地图访问数组的元素?
- 访问数组中的不同元素
- 使用指针访问数组元素时出现意外结果
- 使用指针访问数组的值
- C++基于1而不是0的访问数组,方法是在编译时移位
- 如何在主函数之外访问数组?
- 如何在 llvm 的 cpp api 中使用 CreateInBoundsGEP 来访问数组的元素?
- 访问数组中所有结构的成员
- C 是否每次访问数组时都复制元素?
- C++ 为什么访问数组中的元素会返回指针?
- 如何通过指针访问数组的元素
- 指针数组交换无需直接访问数组
- 直接从指针/地址访问数组的元素
- 我有一个 Qt 对象的 2d 数组,我已经用值播种了这些对象。如何访问数组中特定对象的值并更改它们?
- 如何使用 C+ 中的指针访问数组中的特定索引
- 通过两个下标访问数组成员