lua中的多个for循环

我需要为变量添加多个“for”循环,我认为这不是一个好的方法,我该如何在一个循环中添加多个for循环?虽然这种方法可以工作,但我需要一种正确的方法来实现这一点。

    for i=1, #mush01Plants, 1 do
        if GetDistance... then
            ...
        end
    end
    for i=1, #mush02Plants, 1 do
        if GetDistance... < 1 then
            ...
        end
    end
    for i=1, #mush03Plants, 1 do
        if GetDistance... < 1 then
            ...
        end
    end
点赞
用户8621712
用户8621712

你可以制作一个函数来“模板”代码:

local function GetDistanceForPlants(plants) -- plants would be `mush01Plants`-like tables.
    for i=1, #plants, 1 do
        if GetDistance... then
            ...
        end
    end
end

GetDistanceForPlants(mush01Plants)
GetDistanceForPlants(mush02Plants)
GetDistanceForPlants(mush03Plants)

如果需要从每个表中使用某些内容,则可以使用此函数,否则只需将 #mush01Plants + #mush02Plants + #mush03Plants 合并在一个循环中即可。

2020-11-24 19:53:42
用户3574628
用户3574628

你基本上是在用不同的数组重复相同的一块代码。你可以把这些数组放到一个新的数组中,并通过外部 for 循环迭代它们。

for _, t in ipairs{mush01Plants, mush02Plants, mush03Plants} do
    for i=1, #t, 1 do
        if GetDistance... then
            ...
        end
    end
end
2020-11-24 20:26:37