我定义了两组值:
local A1 = {100, 200, 300, 400}
local A2 = {500, 600, 700, 800}
我想迭代一个循环,将另一个变量B1和B2的值分配为A1和A2中的对,如下所示:
B1 = 100 and B2 = 500 (first iteration)
B1 =200 and B2 = 600 (second iteration)
B1 = 300 and B2 = 700 (third iteration)
B1=400 and B2 = 800 (fourth iteration)
我尝试按如下方式使用ipairs:
for i, f1 in ipairs(A1) do
for j, f2 in ipairs(A2) do
B1 = f1
B2 = f2
end
end
但是这给了我
B1 = 100 and B2 = 500 (first iteration)
B1 =100 and B2 = 600 (second iteration)
B1 = 100 and B2 = 700 (third iteration)
B1=100 and B2 = 800 (fourth iteration)
B1 = 200 and B2 = 500 (fifth iteration)
B1 =200 and B2 = 600 (sixth iteration)
B1 =200 and B2 = 700 (seventh iteration)
....
...
...
so on...
任何人都可以帮助我以正确的方式编码吗?
答案 0 :(得分:3)
您可以使用数字循环轻松完成此操作:
for i = 1, 4 do
local a, b = A1[i], B1[i]
--- use them
end
你如何确定你需要的迭代次数是棘手的部分。如果大小是变体,但每个表的长度与其他表的长度相同,则可以使用长度运算符(#A1
)。
或者,您可能需要一个返回给定表集的最大长度的函数。
local function max_table_len (...)
local tabs = { ... }
local len = 0
for i = 1, #tabs do
local l = #tabs[i]
if l > len then
len = l
end
end
return len
end
甚至可能是一个帮助函数来获取每个值。
local function get_from_tables (index, ...)
local values = { ... }
local len = #values
for i = 1, len do
values[i] = values[i][index]
end
return table.unpack(values, 1, len)
end
以类似的方式结束:
for index = 1, max_table_len(A1, B1) do
local a, b = get_from_tables(index, A1, B1)
end
答案 1 :(得分:1)
您可以在Programming in Lua的ipairs
示例的基础上进行构建。例如,这个版本并行迭代2个序列:
-- iterator function
local function iter_ipairs2(tablePair, i)
i = i + 1
local v1 = tablePair[1][i]
local v2 = tablePair[2][i]
-- if you use 'and' here the iteration stops after finishing
-- the shortest sequence. If you use 'or' the iteration
-- will stop after it finishes the longest sequence.
if v1 and v2 then
return i, v1, v2
end
end
-- this is the function you'll call from your other code:
local function ipairs2(t1, t2)
return iter_ipairs2, {t1, t2}, 0
end
-- usage:
local A1 = {100, 200, 300, 400, 500}
local A2 = {500, 600, 700, 800}
for i, v1, v2 in ipairs2(A1, A2) do
print(i, v1, v2)
end
答案 2 :(得分:0)
以前的答案更详细,并提供更一般和更好的答案。
这个是Lua的新手。它不仅显示了两个循环,而且强调通常有多种方法可以达到你想去的地方。
local A1 = {100, 200, 300, 400}
local A2 = {500, 600, 700, 800}
print("simplest answer:")
-- doesn't use ipairs and assumes A1 and A2 are the same size
for i = 1, #A1 do
B1 = A1[i]
B2 = A2[i]
print(B1, B2, "(iteration #"..i..")")
end
print()
print("answer that uses ipairs:")
-- again, assumes A1 and A2 are the same size
for i, v in ipairs(A1) do
B1 = A1[i] -- i steps through A1 and A2
B2 = A2[i] -- this works because A1 and A2 are same size
print(B1, B2, "(iteration #"..i..")")
end
给出这个输出:
simplest answer:
100 500 (iteration #1)
200 600 (iteration #2)
300 700 (iteration #3)
400 800 (iteration #4)
answer that uses ipairs:
100 500 (iteration #1)
200 600 (iteration #2)
300 700 (iteration #3)
400 800 (iteration #4)