首页 > 解决方案 > lua中的多个for

问题描述

我需要为变量事物制作超过 1 个“for”,我认为这不是一个好方法,如何在 1 个循环中添加多个 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

标签: lua

解决方案


您可以创建一个函数来“模板化”代码:

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在一个循环中求和即可。


推荐阅读