ref: https://blog.csdn.net/ouyangshima/article/details/43339571
LUAand C/C++ the communication bridge——Stack< /span>
Lua was born to interact with C, so use CExpandLuaOr change LuaEmbed in CThese are very popular practices. To understand Cand Lua< Span style="font-size: 14px;">The interactive method, first of all, we must review the Chow the language is Processing function parameters.
CFunctions and parameters
Everyone knows CLanguage is implemented in assembly. There is no concept of function in assembly language. The corresponding function is What is called a sub-process, a sub-process is a piece of instruction, a sub-process and the sub-process it calls through the stack of Perform parameter transfer interaction. Before a sub-process calls other sub-processes, the parameters required by the sub-process to be called will be pushed into the stack according to the agreed format. In the called sub-process , The parameters can be taken out of the stack according to the agreed rules. In the same way, the transfer of the return value is also carried out through the stack. CThe format in which the parameters of the language convention are put into the stack, It’s the “call convention“. CThe function prototype of the language determines the The number and types of parameters put into the stack. p>
Luathe virtual stack
LuaThe interaction between C is cleverly simulated< span style="font-family: SimSun; font-size: 14px;">CLanguage stack,Luaand CMutual calling and Access is carried out through the stack, which ingeniously solves the problem of mutual access between variables of different types. Specifically, let’s imagine the following picture
Because C and Lua are languages of different levels, the C language Variables and variables and functions in Lua cannot directly interact. We assume that C language and Lua have their own “spaces (C Space and Lua Space)”. The interaction between these two spaces is solved by the virtual stack in the figure above. Why use a virtual stack to interact? Its purpose is to provide great flexibility while avoiding the explosion of the combination of two language variable types during interaction.
The use of the stack solves the two differences between C and Lua Coordination issue: First, Lua will automatically perform garbage collection, while C requires the display of the allocated storage unit, which is a contradiction between the two. Second, the confusion caused by the inconsistency between the dynamic types in Lua and the static types in C.
LuaAPI first program
-
/* div>download and install, LuaForWindows software (http://download.csdn.net/download/ivastest/3713327), after installation, there will be two files../lua5.1/inclue/;../lua5.1/lib/, which is The header files and library files we need to use for programming;Or, go to the official website (http://www.lua.org/download.html) to download the source code, compile the library file by yourself, Baidu search (vs2012 compile using lua ) Tutorial1. New, Win32 console application-empty project,2. Configuration, additional include directory, additional library directory, additional dependencies*/
div>
using namespace std;/*#includeThe content is: extern “C” {#include “lua .h”#include “lualib.h”#include “lauxlib.h”}*///#pragma comment(lib, “lua5.1.lib”) // This is the Debug version.//#pragma comment(lib, “lua51.lib”) // This is the Release version./*C language to read and write Lua global variables (basic types)C language reading Lua global variables is the simplest operation. From the above figure, we can guess that if you read the global variables in Lua through the C language, two steps are required: 1. Push the global variables from Lua Space into the virtual stack; 2. Read the global variables from the stack into the C language Space . In the interaction between Lua and C, Lua cannot see and manipulate the virtual stack, but only has the right to manipulate the stack in the C language, so the two steps mentioned above are all done in the C language.*/void get_global(lua_State *L)< /span>{int global_var1;lua_getglobal(L, “global_var1”); /* read the global variable global_var1 from the variable space of lua and put it into the virtual stack*/global_var1 = lua_tonumber(L, -1); /* read the variable that was just pushed onto the stack from the virtual stack, -1 Means to read the top element of the stack*/printf(“Read global var from C: %d
“, global_var1);< /span>}int main()< /span>{lua_State *l = luaL_newstate(); // Create a Lua state. It is actually a data structure.luaL_openlibs(l); // Load all standard libraries, math, table, os, debug,. ..luaL_dofile(l, < span class="hljs-string">“test.lua”);//When debugging, the test.lua file must be in the same directory as the .cpp file; and the code of test.lua must be in ANSI format, otherwise it will Execution failed (0: success), (1: failure)get_global(l);lua_close(l);system( “pause”);return 0;< li>
}/*test.lua file content :print(“Hello world, from “,_VERSION,”!”)global_var1 = 5print(“Print global varb from lua”, global_var1) div>Output:Hello world, from Lua 5.1 !Print global varb from lua 5< /div>
Read global var from C: 5*//*The compilation and execution of Lua scripts are independent of each other and are executed on different threads. You can apply for a virtual machine through the luaL_newstate() function and return the pointer type lua_State. All future calls of other Lua Api functions will require this pointer as the first parameter to specify a virtual machine. So lua_State represents a lua virtual machine object, and luaL_newstate() allocates a virtual machine. The lua library manages all virtual machines. Destroy all objects of the specified virtual machine (if there is no method related to garbage collection, this method will be called) and recover all the memory generated by the dynamic allocation of the virtual machine. On some platforms, we do not need to call this function, because when the master When the program exits, resources will be naturally released, but a long-running program, such as a web server running in the background, needs to immediately reclaim virtual machine resources to avoid excessive memory usage.*/LuaAPI finishing
The header file lua.h defines the basic functions provided by Lua. These include functions to create a new Lua environment (such as lua_open), functions to call Lua functions (such as lua_pcall), functions to read/write global variables in the Lua environment, functions to register new functions that can be called by Lua code, and many more. All defined in lua.h have a lua_ prefix.
The header file lauxlib.h defines the functions provided by the auxiliary library. Similarly, all functions defined in it start with luaL_ (for example, luaL_loadbuffer). The auxiliary library uses the basic functions provided in lua.h to provide a higher level of abstraction; all Lua standard libraries use auxlib. The basic API is dedicated to economy and orthogonality, while auxlib is dedicated to the practicality of general tasks. Of course, it is very easy to create other abstractions based on the needs of your program. It should be kept in mind that auxlib does not have access to Lua. It accomplishes all its work through the official basic API. API Chinese introduction, Lua 5.1 Reference Manual
Stack
Lua operates the stack according to a strict LIFO rule (last in, first out; that is, always access the top of the stack). When you call Lua, it only changes the top part of the stack. Your C code has more freedom; more specifically, you can query any element on the stack, and even insert and delete elements at any position. The elements in the stack are positioned by index values, where the top of the stack is -1, the stack The bottom is 1. Stack member access support index. < span style="color: #ff0000;">It should be noted that the stack operation is based on the top of the stack, that is, it will only manipulate the value at the top of the stack.
C++ data is passed to the virtual stack
-
/* push functions (C -> stack)——>Operation between C space and virtual stack span>
-
C language presses variables that conform to Lua data types (nil, number, string, table, function, userdata, thread) into the virtual stack
- < div class="hljs-ln-code">
LUA_API void (lua_pushnil) (lua_State *L);LUA_API void (lua_pushnumber) (lua_State *L, lua_Number n);–double,float span>LUA_API void (lua_pushinteger) (lua_State *L, lua_Integer n);–int,longLUA_API void (lua_pushlstring) (lua_State *L, const char *s, size_t l);–Any string (char *Type, allow to contain’