经过前面几章的介绍,相信大家对Lua
的堆栈已经比较熟悉了,如果还不是很熟悉的朋友,建议多看几遍前面的教程,或者多敲几次代码。
那么,如果已经对
Lua
的堆栈比较熟悉,接下来的内容就很简单了。
今天我们来看看
C++
如何调用
Lua
的函数,先看看现在
Lua
文件是什么样的:
- -- helloLua.lua文件
- myName = "beauty girl"
- helloTable = {name = "mutou", IQ = 125}
- function helloAdd(num1, num2)
- return (num1 + num2)
- end;
-- helloLua.lua文件
myName = "beauty girl"
helloTable = {name = "mutou", IQ = 125}
function helloAdd(num1, num2)
return (num1 + num2)
end;
我们看到多了个
helloAdd
函数,那么,现在我们要用
C++
调用这个函数。
(旁白:肯定又要用到getglobal了,每次都有它~!= =)
直接上代码了:
- /* C++调用lua的函数 */
- void HelloLua::demo3() {
- lua_State* pL = lua_open();
- luaopen_base(pL);
- /* 执行脚本 */
- luaL_dofile(pL, "helloLua.lua");
- /* 把helloAdd函数对象放到栈中 */
- lua_getglobal(pL, "helloAdd");
- /* 把函数所需要的参数入栈 */
- lua_pushnumber(pL, 10);
- lua_pushnumber(pL, 5);
- /*
- 执行函数,第一个参数表示函数的参数个数,第二个参数表示函数返回值个数 ,
- Lua会先去堆栈取出参数,然后再取出函数对象,开始执行函数
- */
- lua_call(pL, 2, 1);
- int iResult = lua_tonumber(pL, -1);
- CCLOG("iResult = %d", iResult);
- }
/* C++调用lua的函数 */
void HelloLua::demo3() {
lua_State* pL = lua_open();
luaopen_base(pL);
/* 执行脚本 */
luaL_dofile(pL, "helloLua.lua");
/* 把helloAdd函数对象放到栈中 */
lua_getglobal(pL, "helloAdd");
/* 把函数所需要的参数入栈 */
lua_pushnumber(pL, 10);
lua_pushnumber(pL, 5);
/*
执行函数,第一个参数表示函数的参数个数,第二个参数表示函数返回值个数 ,
Lua会先去堆栈取出参数,然后再取出函数对象,开始执行函数
*/
lua_call(pL, 2, 1);
int iResult = lua_tonumber(pL, -1);
CCLOG("iResult = %d", iResult);
}
简单说明一下步骤:
1) 执行脚本
(旁白:我就知道你会说废话。。。)
2) 将
helloAdd
函数放到栈中:
lua_getglobal(pL, “helloAdd”)
。(旁白:看吧,我就知道
~
!)
3) helloAdd
有
2
个参数,我们要把参数传递给
lua
,所以
2
个参数都要放到栈里。
4) 第
2
和第
3
步已经把函数所需要的数据都放到栈里了,接下来只要告诉
lua
去栈里取数据,执行函数
~
! 调用
lua_call
即可,注释已经很详细了,这里就不重复了
转载于:https://blog.51cto.com/zgame/1118565