根据选择插槽在 Lua table 中移动对象的最有效方法是什么?

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

我有一个 table 个对象,用户可以在 table 中以任何给定顺序在 table 中选择一个对象,并将其放在 table 中的另一个插槽中=34=]。当发生这种情况时,我需要 table 从选定的丢弃插槽移动并填充空插槽。不是交换,这很简单,而是放置点的偏移。

所以如果我把这个作为我的 table

的一个高度简化的例子
t = {a, b, c, d, e, f}

用户选择 e,并希望将其放入插槽 b。我会怎样

  1. e 获得 b 名额
  2. 将所有值从“bd右移然后也填充 空的 e 插槽?
  3. 无论选择什么以及在哪里,我将如何处理这种转变 无论 table 的大小如何,它都能有效地移动到 table 可能是?

如果您想将位置 old 的项目按照您的描述移动到位置 new,您可以使用:

table.insert(t, new, table.remove(t,old))

这是你的例子:

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, ','))

至于效率,上面的代码确实将一些元素移动了两次,而这些元素本可以留在原处,但这可能无关紧要,除非 table 很大。

在 Lua 5.3 中,您可以使用 table.move 做一些更好的事情。

这是一个使用 table.move 的 shift 实现,如@lhf 所述,它在 Lua 5.3 中有效且可用:

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