Lua is a lightweight, flexible, and extensible scripting language that can be easily embedded in other languages (C + +), thanks to its powerful C API, which makes it easy to tune in with C + + between them.
Lua calls C
Lua calls the C function, which is actually registering the C function in Lua and passing the C function address to the LUA interpreter. This transmission is to be followed by a protocol, namely:
Copy Code code as follows:
typedef int (*lua_cfunction) (lua_state* L)
Lua and C interact through the stack (state), and when Lua calls the C function, LUA first copies the data onto the stack, then C gets the data from the stack, and the return results are placed on the stack when the call ends. Each data in the stack is positioned by index value, the index value is positive for the offset index relative to the bottom of the stack, the index value is negative to represent the offset index relative to the top of the stack, the index value is 1 or 1 as the starting value, so the stack top index value is always-1, and the bottom index value is always 1. The stack corresponds to a staging point for data between Lua and C, and each C function has its own separate private stack.
Using the C API provided by Lua, it is simple to invoke the C function, such as the following example:
Copy Code code as follows:
#include <math.h>
#include "Lua.h"
#include "Lualib.h"
#include "Lauxlib.h"
static int L_sin (Lua_state *l)
{
Double d = Lual_checknumber (L, 1);
Lua_pushnumber (L, sin (d));
return 1;
}
static const struct LUAL_REG mylib [] = {
{"Lsin", L_sin},
{NULL, NULL}
};
int Luaopen_mylib (lua_state *l)
{
Lual_openlib (L, "Mylib", Mylib, 0);
return 1;
}
Compile the above code into a static resource's so file, add the above code to a file named MYLIB.C, compile it into a static resource file called Libmylib.so, and GCC compiles the statement as follows:
Copy Code code as follows:
GCC Mylib.c-fpic-shared-o libmylib.so
Put the above code in the Lua_cpath directory (lua_cpath directory location instructions to see "LUA Learning Notes (4)-Modules and packages", here is not much to say.
After loading the libmylib.so resource file into the module directory, you can load the require in the Lua code directly, for example, using the following:
Copy Code code as follows:
Require "Mytestlib"
Print (Mylib1.lsin (10))