【Cocos2d-x lua篇005】C++调用Lua的函数
来源:互联网 发布:ubuntu启动anaconda 编辑:程序博客网 时间:2024/05/21 17:57
经过前面几章的介绍,相信大家对Lua的堆栈已经比较熟悉了,如果还不是很熟悉的朋友,建议多看几遍前面的教程,或者多敲几次代码。
那么,如果已经对Lua的堆栈比较熟悉,接下来的内容就很简单了。
今天我们来看看C++如何调用Lua的函数,先看看现在Lua文件是什么样的:
- -- helloLua.lua文件
- myName = "beauty girl"
- helloTable = {name = "mutou", IQ = 125}
- function helloAdd(num1, num2)
- return (num1 + num2)
- end;
我们看到多了个helloAdd函数,那么,现在我们要用C++调用这个函数。
直接上代码了:
- /* 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即可,注释已经很详细了,这里就不重复了。
来,大家忽略旁白,教程什么的还是我来写比较好,主要是,吐槽这工作,不符合我的身份~
本章到此结束,很简单吧?~
下一章我们介绍在Lua中调用C++的函数~
- 【Cocos2d-x lua篇005】C++调用Lua的函数
- 【Cocos2d-x lua篇006】Lua调用C++的函数
- 【木头Cocos2d-x 030】Lua篇(第05章):C++调用Lua的函数
- 【木头Cocos2d-x 031】Lua篇(第06章):Lua调用C++的函数
- 【木头Cocos2d-x 031】Lua篇(第06章):Lua调用C++的函数
- 【木头Cocos2d-x 030】Lua篇(第05章):C++调用Lua的函数
- 【木头Cocos2d-x 030】Lua篇(第05章):C++调用Lua的函数
- 【木头Cocos2d-x 031】Lua篇(第06章):Lua调用C++的函数
- 【木头Cocos2d-x 030】Lua篇(第05章):C++调用Lua的函数
- 【木头Cocos2d-x 031】Lua篇(第06章):Lua调用C++的函数
- 【木头Cocos2d-x 031】Lua篇(第06章):Lua调用C++的函数
- cocos2d-x下c++调用lua函数
- cocos2d-x lua调用c++函数
- cocos2d-x bindings-generator(lua调用c++)
- cocos2d-x bindings-generator(lua调用c++)
- [lua]C调用lua函数
- Cocos2d-x lua的随机函数
- cocos2d-x lua 调用ccbi
- Android主线程里不允许网络操作
- Android手机软件研发环境配置
- 【Cocos2d-x lua篇004】获取Lua表结构数据
- UITabBarController+UINavigationController多层嵌套
- HDU 1029 Ignatius and the Princess IV 【求众数】
- 【Cocos2d-x lua篇005】C++调用Lua的函数
- 在Ubuntu下怎么截图
- Linux系统调用
- 【Cocos2d-x lua篇006】Lua调用C++的函数
- UIWebView加载Loading...两种方法
- 把内容写入指定目录指定文件的java文件工具类,支持日期格式目录名的生成
- UIView详解
- EOJ 1255
- oracle保存小数点前为"0"的问题