Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you swap values in lua tables?

Tags:

lua

How would you swap a value in a table and exchange it for a different one? for example:

local TestTable = {1, 2, 3, 4, 5}
local SwappedTestTable = TestTable:Swap(2, 4)
for i, v in pairs(TestTable) do
    print(v)
end

-- Output = 1, 4, 3, 2, 5

This is what I've tried and it failed horrendously.

local TestTable = {1, 2, 3, 4, 5}

function Swap(Table, Pos1, Pos2)
    local Table = Table
    local Item1 = Table[Pos1]
    local Item2 = Table[Pos2]
    
    table.remove(Table, Pos1)
    table.insert(Table, Pos2, Item1)
    
    table.remove(Table, Pos2)
    table.insert(Table, Pos1, Item2)
    
    return Table
end

for _, v in pairs(Swap(TestTable, 2, 4)) do
    print(v)
end
like image 255
Ivan Avatar asked Sep 16 '25 13:09

Ivan


1 Answers

This is what I've tried and it failed horrendously.

An interesting solution, but plagued by major issues:

  1. It fails to deal with the index shifts the table.insert and table.remove calls cause, causing later table.insert and table.remove calls to operate on the wrong indices (this could be fixed though)
  2. It takes linear time (due to the aforementioned index shifts), which is unacceptable for such a basic operation.
  3. It is overly complex.

How would you swap a value in a table and exchange it for a different one?

I would simply get the two values and set them to the respective "other" index, swapping the values in constant time:

function Swap(Table, Pos1, Pos2)
    local tmp = Table[Pos1]
    Table[Pos1] = Table[Pos2]
    Table[Pos2] = tmp
    return Table
end

Lua allows you to write this even more concise using "multiple assignments":

function Swap(Table, Pos1, Pos2)
    Table[Pos1], Table[Pos2] = Table[Pos2], Table[Pos1]
    return Table
end

(at which point the Swap function becomes superfluous, as it is hardly any shorter or more concise than writing down the assignment each time)

Notes:

  1. If you want to be able to use the Swap function in an OOP fashion (Table:Swap(i, j)), you'll have to assign a metatable. local metatable = {__index = {Swap = Swap}}; setmetatable(Table, metatable) will work for this.
  2. Why does the Swap function return the Table? This is only useful for some syntactic sugar (chaining, f.E. with pairs as in your example) and might be unexpected in a language that distinguishes statements and expressions.
  3. Again, I would probably not use a function for this (especially considering the code necessary to require the function or the global namespace pollution you otherwise need to make it available), but instead simply use the assignments Table[i], Table[j] = Table[j], Table[i].
  4. Your naming convention (which I've sticked to in this post) is somewhat irritating; UpperCamelCase is usually used for class & metatable names in Lua rather than functions and (table) variables.
like image 148
LMD Avatar answered Sep 18 '25 08:09

LMD