In the previous article (C calls the Lua function), we talked about how to call the Lua function in C language. Generally, language a can call language B, which is also true in turn. Just as JNI is used between Java and C languages for intercommunication, Lua and C can also be intertuned.
When Lua calls the C function, it uses the same stack as C calls Lua. The C function obtains the function from the stack and then pushes the result to the stack. To distinguish the returned result from other values in the stack, each function returns the number of results. There is an important concept here: this stack is not a global structure, and each function has its own private local stack. Even if the C function calls the Lua code, the Lua code calls the C function again, and they have their own local stacks. The index of the first parameter is 1. As the first example, let's see how to implement a simple function and return the sum of the given two parameters: static int l_plus (lua_state * l) {lua_integer A = lua_tointeger (L, 1); lua_integer B = lua_tointeger (L, 2); lua_pushinteger (L, A + B); return 1;} Each Lua registered function must be of this prototype, it is already in the Lua. h defines: typedef int (* lua_cfunction) (lua_state * l); because the C function returns the number of returned values of the int type. Therefore, Lua automatically removes any data in the returned value before pushing the return value.
Before using this function in Lua, We need to register it. Use lua_pushcfunction, which accepts a C function, and then creates a value of the function type in Lua to represent the function. Lua_pushcfunction (L, lua_plus); lua_setglobal (L, "myplus ");
A major method is to check its parameter type: static int l_plus (lua_state * l) {lua_integer A = lual_checkinteger (L, 1); lua_integer B = lual_checkinteger (L, 2); lua_pushinteger (L, A + B); return 1 ;}
Code complete:/** http://blog.csdn.net/booirror */# include <Lua. h>
# Include <lauxlib. h>
# Include <lualib. h>
Static int l_plus (lua_state * l)
{
Lua_integer A = lual_checkinteger (L, 1 );
Lua_integer B = lual_checkinteger (L, 2 );
Lua_pushinteger (L, A + B );
Return 1;
}
Int main ()
{
Lua_state * l = lual_newstate ();
Lual_openlibs (L );
Lua_pushcfunction (L, l_plus );
Lua_setglobal (L, "myplus ");
If (lual_dostring (L, "Print (myplus (2, 2 ))")){
Lua_close (L );
Error ("failed to invoke ");
}
Lua_close (L );
Return 0;
} (End)
Lua calls the c Function