当 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 <stdio.h>
- //lua头文件
- #ifdef __cplusplus
- extern "C" {
- #include "lua.h"
- #include <lauxlib.h>
- #include <lualib.h>
- }
- #else
- #include <lua.h>
- #include <lualib.h>
- #include <lauxlib.h>
- #endif
- int 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
运行结果: