1. Introduction
This section describes some Lua APIs for Stack operations and data type determination. You can use these functions to obtain the variable values in the script.
2. Steps
Compile the test01.lua script, create the console C ++ program in vs2003, correctly configure the program, run the result, modify the script test02.lua, and view the execution result.
3. Test script
The following is the Lua script for testing.
Function plustwo (X)
Local A = 2;
Return x +;
End;
Rows = 6;
Cols = plustwo (rows );
The above script defines a function and two global variables (LUA script variables are global by default ). In the subsequent C ++ program, we will obtain the two variables rows and Cols through stack operations.
4. Console Program
# Include <iostream>
Extern "C"
{
# Include "Lua. H"
# Include "lauxlib. H"
# Include "lualib. H"
}
Using namespace STD;
Int main (INT argc, char * argv [])
{
Cout <"01_read_stack" <Endl;
/** // * Create a Lua vmachine */
Lua_state * l = lua_open ();
Luaopen_base (L );
Luaopen_table (L );
Lual_openlibs (L );
Luaopen_string (L );
Luaopen_math (L );
Int ierror;
Ierror = lual_loadfile (L, "../test01.lua ");
If (ierror)
{
Cout <"load script failed! "<Lua_tostring (L,-1) <Endl;
Lua_close (L );
Return 1;
}
Ierror = lua_pcall (L, 0, 0, 0 );
If (ierror)
{
Cout <"pcall failed" <lua_tostring (L,-1) <ierror <Endl;
Lua_close (L );
Return 1;
}
Lua_getglobal (L, "rows ");
Lua_getglobal (L, "Cols ");
If (! Lua_isnumber (L,-2 ))
{
Cout <"[rows] is not a number" <Endl;
Lua_close (L );
Return 1;
}
If (! Lua_isnumber (L,-1 ))
{
Cout <"[Cols] is not a number" <Endl;
Lua_close (L );
Return 1;
}
Cout <"[rows]"
<Static_cast <int> (lua_tonumber (L,-2 ))
<"[Cols]"
<Static_cast <int> (lua_tonumber (L,-1 ))
<Endl;
Lua_pop (L, 2 );
Lua_close (L );
Return 0;
}