当 Lua 调用 C 函数的时候,使用和 C 调用 Lua 同样类型的栈来交互。
C 函数从栈中获取她的參数。调用结束后将返回结果放到栈中。为了区分返回结果和栈中的其它的值,每一个 C 函数还会返回结果的个数(the function returns (in C) the number of results it is leaving on the stack.)。
// luacallcpp.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"#include//lua头文件#ifdef __cplusplusextern "C" {#include "lua.h" #include #include } #else#include #include #include #endifint static add(lua_State* L){ //获取第一个參数 double x=lua_tonumber(L,1); double y=lua_tonumber(L,2); //返回值压栈,压入两个返回值 lua_pushnumber(L,x+y); lua_pushnumber(L,1000); //返回值的个数, return 2;}int _tmain(int argc, _TCHAR* argv[]){ lua_State * L=NULL; /* 初始化 Lua */ L = lua_open(); /* 加载Lua基本库 */ luaL_openlibs(L); /* 执行脚本 */ luaL_dofile(L, "./script/func.lua"); //函数入栈 lua_pushcfunction(L,add); //设置全局函数名 lua_setglobal(L,"Add"); //调用lua函数LUACALLCPP来反调cpp中的add lua_getglobal(L,"LUACALLCPP"); lua_pushnumber(L,10); lua_pushnumber(L,34.33); //两个參数。两个返回值 lua_pcall(L,2,2,0); //取返回值二 printf("lua call cpp return val is %f \n",lua_tonumber(L,-1)); //取返回值一 printf("lua call cpp return val is %f \n",lua_tonumber(L,-2)); /* 清除Lua */ lua_close(L); return 0;}
--region *.lua--Date--此文件由[BabeLua]插件自己主动生成print("func.lua hava been loaded")function LUACALLCPP(x,y)-- 调用c++中的函数return Add(x,y)--print(Add(x,y))end--endregion执行结果: