I have a table of objects, and a user can choose an object in the table at any given order in the table and place it in another slot in the table. When that happens I need the table to shift from the selected dropped slot and fill the empty slot. Not a swap, that's easy, but a shift at the point of placement.
so if I have this as a highly simplified example of my table
t = {a, b, c, d, e, f}
and the user chooses, say e
, and wants to drop it into slot b
. how best would I
e
take the b
slotb
to d
shift right and then also fill
the empty e
slot?If you want to move the item at position old
to position new
as you describe, you can use this:
table.insert(t, new, table.remove(t,old))
Here is your example:
t = {10,20,30,40,50,60}
print(table.concat(t, ','))
old = 5
new = 2
table.insert(t, new, table.remove(t,old))
print(table.concat(t, ','))
As for efficiency, the code above does shift some elements twice when they could have stayed where they were, but this will probably not matter unless the table is huge.
In Lua 5.3, you can probably do something better with table.move
.
Here is an implementation of shift using table.move
which is efficient and available in Lua 5.3 as @lhf mentioned:
function shift(t, old, new)
local value = t[old]
if new < old then
table.move(t, new, old - 1, new + 1)
else
table.move(t, old + 1, new, old)
end
t[new] = value
end
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