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 的工作原理,尤其是上面的粗体字,需要帮助!
最佳答案
堆栈基本上是一个数组,是按明确定义的顺序排列的元素的线性序列。假设我们有一个字符数组,如下所示(从 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
关于lua - lua_rotate 是做什么的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52241580/