The main advantage of LUA as an embedded language is that it is very useful to call the C function with C, which can greatly enrich the development ability of LUA by introducing C Dynamic library into the C functions.
How Lua invokes the C function:
1.Lua can call C function, not that LUA can invoke all C functions, just like C calls Lua, need to follow a certain protocol, LUA can only invoke the registered C function, and also through the virtual stack implementation.
2. The registered C function needs to be fulfilled in the form of:
typedef int (*lua_cfunction) (Lua_state *l);
Cases:
Double Max (double A, double b) {
Return a>b? A:B;
}
static int L_max (Lua_state *l) {
Double NUM1 = Lua_tonumber (L, 1);
Double num2 = Lua_tonumber (L, 2);
Lua_pushnumber (L, Max (NUM1, num2));
return 1;
}
3. Register as C function
" Mymax ");
Call in 4.Lua (Test.lua)
D = Mymax (340,Notoginseng); Io.write (d)
The complete C function
#include"lua.h"#include"Lualib.h"#include"Lauxlib.h"double Max (double A, double b) {returnA>B. a:b;} static int L_max (Lua_state*L) {float NUM1= Lua_tonumber (L,1); Float num2= Lua_tonumber (L,2); Lua_pushnumber (L, Max (NUM1, num2)); return 1;} int main () {lua_state*l =lual_newstate (); Lual_openlibs (L); Lua_pushcfunction (L, L_max); Lua_setglobal (L,"Mymax"); if(Lual_loadfile (L,"Test.lua") || Lua_pcall (L,0,0,0) {printf ("%s", Lua_tostring (L,-1)); }}
Lua calls C function