所以我想在lua中学习metatables,所以我决定学习一些教程。我正在尝试metatables的__add部分。但由于某些原因,我一直在收到错误(尝试在字段上执行算术(nil)
aTable = {}
--Assign the values for the normal table
for x = 1, 10 do
aTable[x] = x
end
-- metatable
mt = {__add = function(table1, table2)
sumTable = {}
for i = 0, #table1 do
sumTable[i] = table1[i] + table2[i]
end
return sumTable
end}
setmetatable(aTable, mt)
newTable = {}
newTable = aTable + aTable
for x = 1, #newTable do
print(newTable[x])
end
此时我很困惑。帮助将受到赞赏
答案 0 :(得分:2)
在__add函数中它应该是:
for i = 1, #table1 do
因为你最初没有设置table [0],而是从索引1开始(确实推荐用于lua-pseudoarrays,许多操作都依赖于它)
答案 1 :(得分:1)
@Ctx是正确的,问题是数组初始化和添加函数中的索引不同。但修复它的最好方法是修改你的__add
函数来处理传递的数组中的'holes',方法是检查它们中的nil条目。
for i = 0, #table1 do
if (table1[i] and table2[i]) then
sumTable[i] = table1[i] + table2[i]
end
end
答案 2 :(得分:1)
缺少另一件事:你没有在结果上设置相同的元表,这意味着虽然aTable+aTable
,aTable+aTable+aTable
之类的东西会起作用,但aTable+aTable+(aTable+aTable)
会失败。
更正并清理版本:
-- metatable
mt = {
__add = function( table1, table2 )
sumTable = {}
for i = 1, #table1 do
sumTable[i] = table1[i] + table2[i]
end
return setmetatable( sumTable, mt )
end,
}
aTable = setmetatable( {}, mt )
--Assign the values for the normal table
for x = 1, 10 do aTable[x] = x end
newTable = aTable + aTable
for x = 1, #newTable do print( newTable[x] ) end
-- and a test for what would have failed:
yetAnotherTable = newTable + newTable
for x = 1, #yetAnotherTable do print( yetAnotherTable[x] ) end