lua - lua_rotate 是做什么的?

标签 lua lua-c++-connection

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/

相关文章:

c++ - 如何使用 C API for Lua 在控制台中打印错误

c++ - lua - 在 C 中存储闭包,在 C 中调用异步

c - 在 c 编译期间使用 luarocks 安装用于 lua 的 yaml 的问题

c++ - 扩展 Lua : check number of parameters passed to a function

memory-leaks - Lua 弱表内存泄漏

arrays - 如何在lua中循环遍历二维数组

variables - lua 变量作用域

c++ - Lua 和 C++ : separation of duties