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
This is what I've tried and it failed horrendously.
An interesting solution, but plagued by major issues:
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)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:
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.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.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]
.UpperCamelCase
is usually used for class & metatable names in Lua rather than functions and (table) variables.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With