lua\_rotate 的作用是什么?

Lua5.3 引入了一个新的 c api:lua_rotate:https://www.lua.org/manual/5.3/manual.html#lua_rotate

Rotates the stack elements between the valid index idx and the top of the stack. The elements are rotated n positions in the direction of the top, for a positive n, or -n positions in the direction of the bottom, for a negative n. The absolute value of n must not be greater than the size of the slice being rotated.

不理解 lua_rotate 是如何工作的,特别是上面加粗的单词,请帮助!

点赞
用户734069
用户734069

栈基本上是一个数组,一个线性序列,呈明确定义的顺序。假设我们有以下字符数组(1基索引在元素上方):

1 2 3 4 5 6
A Q Z G N K

“旋转”是计算机科学中序列元素的常见操作,例如“移位”、“排序”等(这就是为什么Lua手册不详细说明“旋转”元素的含义)。将此数组向左或右旋转n个位置意味着将所有元素向左/右移动n个元素,并将移出数组末尾的元素按其顺序放入新的空区域。

因此,如果我们将上面的数组右旋转2次,则会得到以下结果:

1 2 3 4 5 6
N K A Q Z G

原始的元素 1-4 变成了新版本的元素 3-6,而原始的元素 5-6 变成了新版本的元素 1-2。左旋转的方法类似。

仅旋转数组的一部分意味着只对此操作进行操作,而不干扰数组的其他部分。因此,如果您拿起上面的原始数组并将其向左旋转3个元素,但仅将 3-6 元素受到影响,则会获得以下结果:

1 2 3 4 5 6
A Q K Z G N
2018-09-09 05:57:18