In the previous article we can perform a Lua interpreter in our game code, let's take a look at how to get what we need from the script.
First, let me simply explain the working mechanism of the Lua interpreter, the Lua interpreter itself maintains a runtime stack, pass this runtime stack, the Lua interpreter passes the parameters to the host program, so we can get a script variable. Value:
Lua_pushString (L, "var"); // put the name of the variable into the stack Lua_Gettatbl (L, Lua_GlobalSindex); the value of the variable is now the top
Suppose you have a variable VAR = 100 in the script. You can get this variable value: int var = Lua_tonumber (L, -1);
How is it, isn't it very simple?
Lua defines a macro to make you simple to get a variable: Lua_GeTGlobal (L, Name)
We can get the value of a variable: Lua_GETGLOBAL (L, "Var"); // Variable value Now Stack Top Int var = Lua_tonumber (L, -1);
The complete test code is as follows:
#include "lua.h" #inculde "lauxlib.h" #include "lualib.h"
INT Main (int Argc, char * argv []) {Lua_State * L = Lua_Open (); Luaopen_Base (L); LuaOpen_IO (L);
Const char * buf = "var = 100";
Lua_Dostring (L, BUF);
Lua_GETGLOBAL (L, "Var"); int var = Lua_tonumber (L, -1);
Assert (var == 100);
Lua_Close (L);
Return 0;}