以下给出一个示例,说明当需要Lua函数返回多个结果时,该如何获取栈中的结果,以及Lua脚本该如何编写
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, ans2=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, "foo"); // 指定C++欲调用Lua脚本中的foo函数,此时C++程序会把foo字串推入堆栈
// 将欲传入Lua函数之参数依序推入堆栈
lua_pushnumber(pLua, 3); // num1
lua_pushnumber(pLua, 7); // num2
lua_call(pLua, 2, 2); // 调用Lua函数;这个宏的第二个参数是所指定之Lua函数的参数数量,宏的第三个参数是该函数返回值的数量
// Lua将参数及函数名依序取出堆栈,然后调用函数,并把结果依序推入堆栈
if(lua_isnumber(pLua, 1)!=0) // 判断堆栈中的值是否为我们要的数字型态的值,若返回非0则正確
{
ans = (int)lua_tonumber(pLua, 1); // 取出堆栈中的函数返回值
}
if(lua_isnumber(pLua, 2)!=0) // 判断堆栈中的值是否为我们要的数字型态的值,若返回非0则正確
{
ans2 = (int)lua_tonumber(pLua, 2); // 取出堆栈中的函数返回值
}
printf("%d %d\n", ans, ans2);
lua_close(pLua);
system("pause");
return;
}
Lua脚本
function foo(num1, num2)
return (num1 * num2), (num1 + num2)
end
Output:
21 10