cocos2dx java 调用lua_cocos2dx之C++调用Lua

本文详细介绍了在Cocos2d-x项目中,如何从C++层面调用Lua脚本进行交互,包括引入头文件、导入Lua文件、编写Lua函数以及在C++中调用无参数、有参数的Lua函数,并展示了读取Lua变量和table的方法。在实际操作中需要注意,被调用的Lua函数不能声明为local。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.引入头文件

#include "cocos2d.h"

#include "CCLuaEngine.h"

USING_NS_CC;

using namespace std;

extern "C"{

#include "lua.h"

#include "lualib.h"

#include "lauxlib.h"

}

2导入Lua文件

如果是cocos2dx的Lua工程只需要在main.lua里面引用就可以了

5e7918160df02ca7d210046e9ede18b3.png

3.Lua文件编写

--Lua变量

strTemp = "乐逍遥"

--Lua的table

tableTemp = {name = "乐逍遥Jun", uuid = "001"}

--没有参数的函数

function test()

return 100

end

--有参数的函数

function testadd(a,b,str)

local c = a+b

return c, str

end

4.C++中的调用

首先是找到AppDelegate.cpp中的

#if (COCOS2D_DEBUG > 0) && (CC_CODE_IDE_DEBUG_SUPPORT >0)

将 CC_CODE_IDE_DEBUG_SUPPORT的值改为0

如果是没有参数只有一个int返回值的Lua函数只需要调用cocos2dx封装好的executeGlobalFunction函数就行

auto engine = LuaEngine::getInstance();

engine->executeGlobalFunction("test");

如果是比较负责的函数

LuaStack * L =LuaEngine::getInstance()->getLuaStack();

lua_State* tolua_s = L->getLuaState();

//--------有参数和返回值的Lua函数的调用---------

lua_getglobal(tolua_s, "testadd");    // 获取函数,压入栈中

lua_pushnumber(tolua_s, 10);          // 压入第一个参数

lua_pushnumber(tolua_s, 20);          // 压入第二个参数

lua_pushstring(tolua_s, "测试");       // 压入第三个参数

int iRet= lua_pcall(tolua_s, 3, 2, 0);// 调用函数,调用完成以后,会将返回值压入栈中,2表示参数个数,1表示返回结果个数。

if (iRet)                       // 调用出错

{

const char *pErrorMsg = lua_tostring(tolua_s, -1);

CCLOG("错误-------%s",pErrorMsg);

return ;

}

int fValue = lua_tonumber(tolua_s, -2);     //获取第一个返回值

string str = lua_tostring(tolua_s, -1);     //获取第二个返回值

CCLOG("有参数和返回值的Lua函数的调用---%d---,%s",fValue,str.c_str());

//--------------读取Lua的变量------------

lua_getglobal(tolua_s, "strTemp");

string strTemp = lua_tostring(tolua_s, -1);

CCLOG("读取Lua的变量---%s",strTemp.c_str());

//-------------读取Lua的table-----------

lua_getglobal(tolua_s,"tableTemp");

lua_getfield(tolua_s,-1,"name");

string strName = lua_tostring(tolua_s,-1);

CCLOG("读取Lua的table--%s",strName.c_str());

5.注意事项

1.如果你是cpp调用lua函数,那么你的这个lua函数不能是local的

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值