gpt4 book ai didi

arrays - Lua: "dragging"数组中的元素序列

转载 作者:行者123 更新时间:2023-12-02 09:40:07 25 4
gpt4 key购买 nike

我正在尝试创建一个函数,将连续数量的元素“拖动”到数组中的新位置,并限制为数组的当前大小。其他项目应该围绕“拖动”的项目晃动。

例如,如果我的数组有 7 个元素,我想拖动中间的三个...

1, 2, 3, 4, 5, 6, 7  <-- keys
a, b, C, D, E, f, g <-- values

大写字符是我想要“拖动”的字符。如果我拖动到数组的开头(拖动到 1),数组将如下所示:

1, 2, 3, 4, 5, 6, 7  <-- keys
C, D, E, a, b, f, g <-- values

如果我拖动到位置 5(或以上 - 不能拖动到当前数组大小之外),数组将如下所示:

1, 2, 3, 4, 5, 6, 7  <-- keys
a, b, f, g, C, D, E <-- values

知道如何以一种不简单的方式使用 Lua 来实现这一点吗?

最佳答案

这是使用 table.move 的版本Lua 5.3 中可用。

它复制要拖动到另一个表中的组,并向上或向下移动值以为该组腾出空间。

 function drag(t, src, len, dest)
local copy = table.move(t, src, src + len - 1, 1, {})

if src >= dest then
table.move(t, dest, src - 1, dest + len)
else
table.move(t, src + len, dest + len - 1, src)
end

table.move(copy, 1, len, dest, t)
end

关于arrays - Lua: "dragging"数组中的元素序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32130855/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com