The Stack
- A stack is used to interface between C and Lua
- Values and functions can be pushed onto it and then executed
Various Stack Operations are Shown in the Code Below
#include <stdio.h> #include <string.h> #include "lua.h" #include "lauxlib.h" #include "lualib.h" static void stackDump(lua_State *L) { int i; int top = lua_gettop(L); /* get the stack depth */ for (i = 1; i <= top; i++) { int t = lua_type(L, i); switch (t) { case LUA_TSTRING: { /* strings */ printf("'%s' ", lua_tostring(L, i)); break; } case LUA_TBOOLEAN: { /* boolean */ printf(lua_toboolean(L, i) ? "true " : "false "); /* print them as strings */ break; } case LUA_TNUMBER: { /* number */ printf("%g ", lua_tonumber(L, i)); break; } default: { /* other values */ printf("%s ", lua_typename(L, t)); break; } } } } int main(void) { lua_State *L = luaL_newstate(); /* opens Lua */ lua_pushboolean(L, 1); /* item 1 also item -4 on the stack after 4 pushes */ lua_pushnumber(L, 10); lua_pushnil(L); lua_pushstring(L, "hello"); stackDump(L); printf("%s", "\n"); lua_pushvalue(L, -4); stackDump(L); /* push a copy of element at index -4 */ printf("%s", "\n"); lua_replace(L, 3); stackDump(L); /* get the top and put it at index 3 */ printf("%s", "\n"); lua_settop(L, 6); stackDump(L); /* set the stack size to 6, put nils */ printf("%s", "\n"); lua_remove(L, -3); stackDump(L); /* remove the item at -3 */ printf("%s", "\n"); lua_settop(L, -5); stackDump(L); /* pop -()n -1 or 4 elements from the stack */ printf("%s", "\n"); return 0; }