如何获得 LUA 中 2 个表的总和?
How do I get the sum of 2 tables in LUA?
x = {1, 2, 3}
y = {4, 5, 6}
z = x + y
我有两个 tablex 和 y,只想创建第三个,它只是其中元素的总和。我努力使用上面的 LUA 代码,但这给出了错误 input:3: attempt to perform arithmetic on a table value (global 'x')...
喜欢,我想要结果z = {5, 7, 9}
请推荐有用的函数,或者请帮助我在LUA中形成这样的函数。
谢谢
是的,迭代并检查 table.concat()
做...
x = {1, 2, 3}
y = {4, 5, 6}
z = {}
-- First check same table length and if so then add sums to z table
if #x==#y then
for i=1,#x do
z[i]=x[i]+y[i]
end
end
print(table.concat(z,' '))
-- puts out: 5 7 9
...结束
您不能在 Lua 中添加 table,除非您实现了 __add
元方法。
对于两个序列的元素明智的总和,只需这样做:
function sumElements(t1,t2)
local result = {}
for i = 1, math.min(#t1, #t2) do
result[i] = t1[i] + t2[i]
end
return result
end
当然你应该验证你的输入并考虑你想如何处理不匹配的 table 大小。假设 t1 有 3 个元素,t2 有 5 个,你是只有 3 个结果值还是将 0 添加到剩余的 2 个?
x = {1, 2, 3}
y = {4, 5, 6}
z = x + y
我有两个 tablex 和 y,只想创建第三个,它只是其中元素的总和。我努力使用上面的 LUA 代码,但这给出了错误 input:3: attempt to perform arithmetic on a table value (global 'x')...
喜欢,我想要结果z = {5, 7, 9}
请推荐有用的函数,或者请帮助我在LUA中形成这样的函数。 谢谢
是的,迭代并检查 table.concat()
做...
x = {1, 2, 3}
y = {4, 5, 6}
z = {}
-- First check same table length and if so then add sums to z table
if #x==#y then
for i=1,#x do
z[i]=x[i]+y[i]
end
end
print(table.concat(z,' '))
-- puts out: 5 7 9
...结束
您不能在 Lua 中添加 table,除非您实现了 __add
元方法。
对于两个序列的元素明智的总和,只需这样做:
function sumElements(t1,t2)
local result = {}
for i = 1, math.min(#t1, #t2) do
result[i] = t1[i] + t2[i]
end
return result
end
当然你应该验证你的输入并考虑你想如何处理不匹配的 table 大小。假设 t1 有 3 个元素,t2 有 5 个,你是只有 3 个结果值还是将 0 添加到剩余的 2 个?