Steven S
Steven S

Reputation: 61

Multiple for in in lua

i need to make more than 1 "for" for the variable thing , i dont think this is a good way to do it , how do i add multiple for in 1 loop? its working but i need a correct way to do this

    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

Upvotes: 1

Views: 478

Answers (2)

luther
luther

Reputation: 5554

You're basically repeating the same chunk of code with a different array each time. You could put those arrays into a new array and iterate through them with an outer for loop.

for _, t in ipairs{mush01Plants, mush02Plants, mush03Plants} do
    for i=1, #t, 1 do
        if GetDistance... then
            ...
        end
    end
end

Upvotes: 2

Spar
Spar

Reputation: 1762

You can make a function to "template" the code:

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)

This function would be useful if you need to use something from each table, if not, just sum #mush01Plants + #mush02Plants + #mush03Plants together in one loop.

Upvotes: 3

Related Questions