Search code examples
listloopsluashift

Shift the array as loop


How can I shift the list as a loop? The input:

local connections = {1, 1, 0, 1}

Needed result:

local variants = {
    {1, 1, 0, 1}, -- as original table
    {1, 1, 1, 0}, -- shifted once to the right
    {0, 1, 1, 1}, -- shifted twice
    {1, 0, 1, 1}, -- shifted three times
}

Solution

  • You want to perform a shift with "wraparound" / "circular" shift. [table.move], as pointed out by lhf, is almost what you need, but lacks the "circular part" and is unavailable on older versions of Lua (such as 5.1, which is still in widespread use). I thus propose implementing this in Lua as below, particularly if you want a new table:

    local function cyclic_table_shift(tab, shift)
        local len = #tab
        local shifted = {}
        for i = 1, len do
            shifted[i] = tab[(i - 1 - shift) % len + 1] -- mod to make it wrap
        end
        return shifted
    end
    

    this yields the correct results for your example:

    > connections = {1, 1, 0, 1}
    > function cyclic_table_shift(tab, shift)
    >>     local len = #tab
    >>     local shifted = {}
    >>     for i = 1, len do
    >>         shifted[i] = tab[(i - 1 - shift) % len + 1] -- mod to make it wrap
    >>     end
    >>     return shifted
    >> end
    > table.unpack(cyclic_table_shift(connections, 0))
    1   1   0   1
    > table.unpack(cyclic_table_shift(connections, 1))
    1   1   1   0
    > table.unpack(cyclic_table_shift(connections, 2))
    0   1   1   1
    > table.unpack(cyclic_table_shift(connections, 3))
    1   0   1   1