gamedesigngeek
gamedesigngeek

Reputation: 43

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

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?

Upvotes: 4

Views: 3750

Answers (2)

lhf
lhf

Reputation: 72312

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.

Upvotes: 5

ryanpattison
ryanpattison

Reputation: 6251

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

Upvotes: 5

Related Questions