Second, the operation of the stack
Because Lua communicates with C + + through the stack, LUA provides the C API to manipulate the stack.
Let's look at one of the simplest examples:
#include <iostream> #include <string.h> using namespace std; extern "C" { #include "lua.h" #include "lauxlib.h" #include "lualib.h" } void Main () { //1. Create a state lua_state *l = Lual_newstate (); 2. Into the stack operation lua_pushstring (L, "I am so Cool~"); Lua_pushnumber (l,20); 3. Value Operation if (lua_isstring (l,1)) { //determine if it can be converted to string cout<<lua_tostring (l,1) <<endl; Convert to string and return } if (Lua_isnumber (l,2)) { cout<<lua_tonumber (l,2) <<endl; } 4. Close State lua_close (L); return; }
It can be simply understood that Lual_newstate returns a pointer to the stack, and other comments should be understood.
Some other stack operations:
int lua_gettop (lua_state *l); Returns the top index of the stack (that is, the stack length) void lua_settop (lua_state *l, int idx); void Lua_pushvalue (lua_state *l, int idx);//pushes a copy of the value on the IDX index into the top void lua_remove (lua_state *l, int IDX); Remove the value on the IDX index void Lua_insert (lua_state *l, int idx); Pop up the top of the stack element and insert the index idx position void lua_replace (lua_state *l, int idx); POPs the top element of the stack and replaces the value of the index IDX position
Ua_settop Sets the top of the stack to a specified position, which is to modify the number of elements in the stack. If the value is higher than the original stack, then the high part nil complements, if the value is lower than the original stack, then the portion of the original stack is discarded. So You can use Lua_settop (0) to empty the stack .
Lua and C + + interactions summarize _2_ stack operations in detail