When Lua calls the C function, it uses the same type of stack as C to invoke Lua to interact with.
The C function gets her number of references from the stack. The return result is placed on the stack when the call ends. To differentiate between the returned results and other values in the stack, each C function returns the number of results (the function returns (in C) of the results it was leaving on the stack. )。
Luacallcpp.cpp: Defines the entry point of the console application. #include "stdafx.h" #include <stdio.h>//lua header file #ifdef __cplusplusextern "C" {#include "lua.h" #include < lauxlib.h> #include <lualib.h>} #else # include <lua.h> #include <lualib.h> #include <lauxlib.h& gt; #endifint static Add (lua_state* L) {//Gets the first parameter double x=lua_tonumber (l,1);d ouble y=lua_tonumber (l,2);//return value pressure stack, Press into two return values Lua_pushnumber (l,x+y); Lua_pushnumber (l,1000);//number of return values, return 2;} int _tmain (int argc, _tchar* argv[]) {lua_state * l=null;/* initialize LUA */L = Lua_open (); /* Load LUA Basic library */Lual_openlibs (L); /* Execute script */lual_dofile (L, "./script/func.lua"); function into the stack lua_pushcfunction (l,add);//Set the global function name Lua_setglobal (L, "add");//Call the LUA function luacallcpp to sung the Addlua_getglobal in CPP (L, " Luacallcpp "); Lua_pushnumber (l,10); Lua_pushnumber (l,34.33);//two parameters. Two return values Lua_pcall (l,2,2,0),///Take the return value two printf ("Lua Call CPP return val is%f \ n", Lua_tonumber (l,-1));//Take the return value one printf ("Lua call CPP return val is%f \ n ", Lua_tonumber (l,-2));/* Clear Lua */lua_close (L); return 0;}
--region *.lua--date--This file is actively generated by the [Babelua] plugin itself print ("Func.lua Hava been Loaded") function Luacallcpp (x, y)--call C + + The function in the return add (x, y)--print (Add (x, y)) end--endregion
Execution Result:
Introduction to LUA II: C + + calls to LUA and the acquisition of multiple function return values