在lua中是以函数指针的形式调用函数, 并且所有的函数指针都必须满足如下此种类型:
typedef int (*lua_CFunction) (lua_State *L);
也就是说,在C++中定义函数时必须以lua_State为参数,以int为返回值才能被Lua所调用。由于lua_State是支持栈的, 所以通过栈可以传递无穷个参数, 大小只受内存大小限制,而返回的int值也只是指返回值的个数真正的返回值都存储在lua_State的栈中。看以下示例:
新建一个c++的vs2010项目,选择win32控制台应用程序,起名LuaTestC,生成项目,打开LuaTestC.cpp文件,c++功能函数创建和注册:
#include "stdafx.h" #include <stdio.h> extern "C"{ #include "lua.h" #include "lualib.h" #include "lauxlib.h" }; #pragma comment(lib, "lua51.lib") lua_State* p_state; //全局函数 static int cal_average(lua_State* L) { //返回栈中元素的个数 int n = lua_gettop(p_state); double sum = 0; int i; for(i = 1; i <= n; i++) { if(!lua_isnumber(p_state,i)) { lua_pushstring(p_state,"average输入参数错误!"); lua_error(p_state); } //将第i个栈的内容取出来赋给sum,再相加 sum += lua_tonumber(p_state,i); } //算出平均值 lua_pushnumber(p_state, sum / n); //算出总和 lua_pushnumber(p_state, sum); //2个返回值 return 2; } //带命名空间的函数库 namespace MyLib { static int sendMessage(lua_State* L) { printf("[玩家] %s \n",lua_tostring(p_state,1)); //没有返回值 return 0; } static int promptMessage(lua_State* L) { lua_pushstring(p_state,"[系统] 发现了1级宠物!"); //1个返回值 return 1; } } static const struct luaL_Reg regFunctions[] = { {"sendMessage", MyLib::sendMessage}, {"promptMessage", MyLib::promptMessage}, {NULL, NULL} }; int _tmain(int argc, _TCHAR* argv[]) { //加载Lua引擎 p_state = lua_open(); luaL_openlibs(p_state); //注册C++函数 lua_register(p_state,"cal_average",cal_average); //打包注册的函数 luaL_register(p_state,"MyLib",regFunctions); luaL_dofile(p_state,"d:/lua/testc.lua"); //关闭Lua引擎 lua_close(p_state); getchar(); return 0; }
testc.lua的脚本内容:
avg,sum = cal_average(10,20,30,40,50,60); print("平均值为:"..avg); print("总和为:"..sum); MyLib.sendMessage("正在抓宠物..."); info = MyLib.promptMessage(); print(info);
运行结果: