Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What would be the most efficient way to shift objects in a Lua table based on choosing a slot?

Tags:

lua

lua-table

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

  1. have e take the b slot
  2. have all the values from "b to d shift right and then also fill the empty e slot?
  3. how would I handle this shift no matter what one is chosen and where its moved in the table efficiently no matter what size the table might be?
like image 911
gamedesigngeek Avatar asked Sep 14 '25 11:09

gamedesigngeek


2 Answers

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.

like image 108
lhf Avatar answered Sep 16 '25 09:09

lhf


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
like image 34
ryanpattison Avatar answered Sep 16 '25 11:09

ryanpattison