lualua-c++-connection

what does lua_rotate do?


Lua5.3 introduced a new 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.

cannot understand the how lua_rotate works, especially above bold words, need help!


Solution

  • The stack is basically an array, a linear sequence of elements in a well-defined order. So let's say we have an array of characters as follows (the 1-based indices are above the elements):

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

    "Rotation" is a common operation on sequences of elements in computer science, much like "shifting" or "sorting" or so forth (this is why the Lua manual doesn't bother to go into detail on what it means to "rotate" elements). To rotate this array to the left or right by some number N means to shift all of the elements left/right by N elements, and to put the elements shifted off of the end of the array in the newly empty part, in their sequential order.

    So if we do a right-rotate of the above array by 2, you get the following:

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

    Elements 1-4 in the original became elements 3-6, and elements 5-6 in the original became 1-2 in the new version. Left rotation works similarly.

    Rotating part of an array merely means doing this operation, but leaving other parts of the array alone. So if you take the original above array, and do a left-rotate by 3 elements, but only affecting elements 3-6, you get the following:

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