LUA:"拖"阵列中的元素的顺序 [英] Lua: "dragging" sequence of elements within array
问题描述
我试图创建一个函数,'拖'元素的数组中的新位置,约束到阵列的电流大小的顺序号。其他项目应轻摇轮'拖'项目。
I'm trying to create a function that 'drags' a sequential number of elements to a new location within the array, constrained to the current size of the array. Other items should jiggle round the 'dragged' items.
例如,如果我的数组有7个元素,我想拖动中间三...
For example, if my array has 7 elements and I want to drag the middle three...
1, 2, 3, 4, 5, 6, 7 <-- keys
a, b, C, D, E, f, g <-- values
大写字符是我要'拖'的人。如果我拖到启动阵列(拖动1)数组是这样的:
The uppercase chars are the ones I want to 'drag'. If I drag to start of the array (drag to 1) the array would look like this:
1, 2, 3, 4, 5, 6, 7 <-- keys
C, D, E, a, b, f, g <-- values
如果我拖到5位(或以上 - 不能被当前的数组大小拖累外)数组是这样的:
If I drag to position 5 (or above - can't be dragged outside current array size) the array would look like this:
1, 2, 3, 4, 5, 6, 7 <-- keys
a, b, f, g, C, D, E <-- values
任何想法,我怎么能做到这一点在非这些混沌的方式使用Lua?
Any idea how I can achieve that using Lua in a non-crufty manner?
推荐答案
下面是一个使用的 table.move
在Lua 5.3。可用
Here is a version using table.move
available in Lua 5.3.
它复制组被拖进另一个表和转移值向上或向下腾出空间的组。
It copies the group to be dragged into another table and shifts values up or down to make room for the group.
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
这篇关于LUA:&QUOT;拖&QUOT;阵列中的元素的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!