luaroblox

How could i loop through every OTHER element in a table in Roblox.lua


I am trying to loop through every other element in an table but I cannot find a way to do so.

Any help is appreciated.

Thank you.


Solution

  • It depends what kind of table you're working with. If you have an array-like table, you can use a simple for-loop:

    local t = {1, 2, 3, 4, 5, 6, 7, 8}
    
    -- start at 1, loop until i > the length of t, increment i by 2 every loop
    for i = 1, #t, 2 do
        local val = t[i]
        print(val) -- will print out : 1, 3, 5, 7
    end
    

    But if you have a dictionary-like table, you will need something to track which key to skip. You could use a simple boolean to keep track, but be aware that there is no guaranteed order of a dictionary-like table.

    local t = {
        a = 1,
        b = 2,
        c = 3,
        d = 4,
    }
    
    local shouldPrint = true
    for k, v in pairs(t) do
        -- only print the value when it's true
        if shouldPrint then
            print(k, v) -- will probably print    a, 1   and   c, 3
        end
    
        -- swap shouldPrint's value every loop
        shouldPrint = not shouldPrint
    end