Deepen the interaction between Lua and C through the Demo program.
This article mainly uses the Demo program to deepen the interaction between Lua and C. It involves interaction, which can be divided:
How to call the Lua function in Function C
Here we will first describe how to call the Lua function in C. Imagine how C communicates with Lua and how can I tell it that I call the xxx parameter?
Lua uses the stack for interaction. Lua provides the c api for Stack operations. It uses various Lua_pushXXX to push different values into the stack, then, when the Lua script is called, the parameter will be removed from the stack and the Lua stack status needs to be maintained by the user. If multiple threads operate on the Lua stack at the same time, the stack status will be disordered if no lock protection is provided.
Hello. lua
Str = "hello world" -- Define a tabtb = {name = "hello", id = 20180119}
Note:Use -- as annotation for Lua
Main. c
# Include
# Include
# Include
# Include
# Include
Int main (void) {char * str; lua_State * L; int li; L = luaL_newstate ();/* Create a Lua VM */luaL_openlibs (L ); /* load the basic Lua library */luaL_loadfile (L, "hello. lua ");/* load the Lua file, but do not run */lua_pcall (L, 0, 0, 0);/* run the Lua file, number of parameters, * /// luaL_dofile (L, "hello. lua "); li = lua_gettop (L);/* return the top index of the stack (that is, the stack length) */lua_getglobal (L," str ");/* obtain the str value, push to stack */str = lua_tostring (L, 1);/* output stack, convert the Lua value at the given index to a C string */printf ("str = % s \ n", str );}
Lua_getglobal (L, "str ")
Execute two steps: first put str into the stack, then Lua will go to the global table to match the str value, and return the str value to the top of the stack.
LuaL_dofile (L, "helloscript. lua ");
It is defined as follows:
# Define luaL_dofile (L, fn) (LuaL_loadfile (L, filename) | lua_pcall (L, 0, LUA_MULTRET, 0) is equivalent to luaL_loadfile + lua_pcall, not only loading but also running <