这次的教程内容和上一篇差不多,只是把获取变量换成调用函数及获取返回结果的概念,內容不多
详细说明都在代码的注释中,我就不多说了,直接看代码吧
代码沿用前一篇的架构,差別只在於新增调用函数的部分而已
C++代码
#include "include\lua.h"
#include "include\lauxlib.h"
#include "include\lualib.h"
#include "windows.h"
void main(int argc, char* argv[])
{
int ans=0;
lua_State *pLua = luaL_newstate(); // Lua5.2后的版本遗弃lua_open(),改用luaL_newstate()
if(!pLua)
{
printf("Failed to open Lua.\n");
return;
}
luaL_openlibs(pLua); // Lua5.1以上使用此函数开启库
if(luaL_dofile(pLua, "luaDemo.lua")!=0) // 执行Lua腳本,若返回0则成功
{
printf("Failed to run lua.\n");
return;
}
lua_settop(pLua, 0); // Lua堆栈栈顶索引重置为0
lua_getglobal(pLua, "multiply"); // 指定C++欲调用Lua脚本中的multiply函数,此时C++程序会把multiply字串推入堆栈
// 将欲传入Lua函数之参数依序推入堆栈
lua_pushnumber(pLua, 3); // num1
lua_pushnumber(pLua, 7); // num2
lua_call(pLua, 2, 1); // 调用Lua函数;这个宏的第二个参数是所指定之Lua函数的参数数量,宏的第三个参数是该函数返回值的数量
// Lua将参数及函数名依序取出堆栈,然后调用函数,并把结果依序推入堆栈
if(lua_isnumber(pLua, -1)!=0) // 判断堆栈顶的值是否为我们要的数字型态的值,若返回非0则正確
{
ans = (int)lua_tonumber(pLua, -1); // 取出堆栈栈顶的值
}
printf("%d\n", ans);
lua_close(pLua);
system("pause");
return;
}
Lua脚本
function multiply(num1, num2)
result = num1 * num2
return result
end
Output:
21