经过前面几章的介绍,相信大家对Lua 的堆栈已经比较熟悉了,如果还不是很熟悉的朋友,建议多看几遍前面的教程,或者多敲几次代码。
那么,如果已经对 Lua 的堆栈比较熟悉,接下来的内容就很简单了。
今天我们来看看 C++ 如何调用 Lua 的函数,先看看现在 Lua 文件是什么样的:
  1. -- helloLua.lua文件  
  2. myName = "beauty girl"  
  3.   
  4. helloTable = {name = "mutou", IQ = 125}  
  5.   
  6. function helloAdd(num1, num2)  
  7.     return (num1 + num2)  
  8. end;  
-- helloLua.lua文件
myName = "beauty girl"
helloTable = {name = "mutou", IQ = 125}
function helloAdd(num1, num2)
	return (num1 + num2)
end;

 
我们看到多了个 helloAdd 函数,那么,现在我们要用 C++ 调用这个函数。
(旁白:肯定又要用到getglobal了,每次都有它~= =
 
直接上代码了:
  1. /* C++调用lua的函数 */  
  2. void HelloLua::demo3() {  
  3.     lua_State* pL = lua_open();  
  4.     luaopen_base(pL);  
  5.   
  6.     /* 执行脚本 */  
  7.     luaL_dofile(pL, "helloLua.lua");  
  8.   
  9.     /* 把helloAdd函数对象放到栈中 */  
  10.     lua_getglobal(pL, "helloAdd");  
  11.   
  12.     /* 把函数所需要的参数入栈 */  
  13.     lua_pushnumber(pL, 10);  
  14.     lua_pushnumber(pL, 5);  
  15.   
  16.     /*  
  17.         执行函数,第一个参数表示函数的参数个数,第二个参数表示函数返回值个数 , 
  18.         Lua会先去堆栈取出参数,然后再取出函数对象,开始执行函数 
  19.     */  
  20.     lua_call(pL, 2, 1);  
  21.   
  22.     int iResult = lua_tonumber(pL, -1);  
  23.     CCLOG("iResult = %d", iResult);  
  24. }  
/* 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 即可,注释已经很详细了,这里就不重复了