3.3 – Stack Manipulation

The API offers the following functions for basic stack manipulation:

  1. void lua_settop (lua_State *L, int index);
  2. void lua_pushvalue (lua_State *L, int index);
  3. void lua_remove (lua_State *L, int index);
  4. void lua_insert (lua_State *L, int index);
  5. void lua_replace (lua_State *L, int index);

lua_settop accepts any acceptable index, or 0, and sets the stack top to that index. If the new top is larger than the old one, then the new elements are filled with nil. If index is 0, then all stack elements are removed. A useful macro defined in the lua.h is

  1. #define lua_pop(L,n) lua_settop(L, -(n)-1)

which pops n elements from the stack.

lua_pushvalue pushes onto the stack a copy of the element at the given index. lua_remove removes the element at the given position, shifting down the elements above that position to fill the gap. lua_insert moves the top element into the given position, shifting up the elements above that position to open space. lua_replace moves the top element into the given position, without shifting any element (therefore replacing the value at the given position). All these functions accept only valid indices. (You cannot call lua_remove or lua_insert with pseudo-indices, as they do not represent a stack position.)

As an example, if the stack starts as 10 20 30 40 50* (from bottom to top; the `*´ marks the top), then

  1. lua_pushvalue(L, 3) --> 10 20 30 40 50 30*
  2. lua_pushvalue(L, -1) --> 10 20 30 40 50 30 30*
  3. lua_remove(L, -3) --> 10 20 30 40 30 30*
  4. lua_remove(L, 6) --> 10 20 30 40 30*
  5. lua_insert(L, 1) --> 30 10 20 30 40*
  6. lua_insert(L, -1) --> 30 10 20 30 40* (no effect)
  7. lua_replace(L, 2) --> 30 40 20 30*
  8. lua_settop(L, -3) --> 30 40*
  9. lua_settop(L, 6) --> 30 40 nil nil nil nil*