cocos2d-x接入支付等sdk时,如果逻辑写在lua端,经常会用到lua与java的交互,下面通过一个实例来实现lua与java的交互过程

一、lua端

lua中使用luaj.callStaticMethod调用java静态方法

local function onCallBack(msg)
--回调处理
if msg == "success"
--
end
end
local function callJavaCallBackLua()
local luaj = require "cocos.cocos2d.luaj"
local className = "org/cocos2dx/cpp/AppActivity"
local args = { "test", onCallBack }
local sigs = "(Ljava/lang/String;I)V"
local ok = luaj.callStaticMethod(className,"callJavaMethod",args,sigs)
end
以上实现通过lua端调用java的静态方法callJavaMethod,并传入2个参数,一个字符串“test”和一个回调函数onCallBack

二、java端

cocos2d-x提供了Cocos2dxLuaJavaBridge带有如下方法可以使用:

public static native int callLuaFunctionWithString(int luaFunctionId, String value); // 调用局部Lua-Function
public static native int callLuaGlobalFunctionWithString(String luaFunctionName, String value); // 调用全局Lua-Function
public static native int retainLuaFunction(int luaFunctionId); // retain一次Lua-Function
public static native int releaseLuaFunction(int luaFunctionId); // release掉Lua-Function
在这里我们使用调用局部Lua-Function callLuaFunctionWithString来做示例

在AppActivity.java合适位置中加入代码

import org.cocos2dx.lib.Cocos2dxLuaJavaBridge;
static int luaFuncCallback = 0;
public static void callJavaMethod(final String test, final int luaFunc){
//Java中可以直接回调这个函数,也可以先保存下来这个注册的Lua局部函数,一般都是保存下来,等待启用SDK充值逻辑走完后再回调
luaFuncCallback = luaFunc;
}
mainActivity.runOnGLThread(new Runnable() {
@Override
public void run() {
Cocos2dxLuaJavaBridge.callLuaFunctionWithString(luaFuncCallback, "success");
Cocos2dxLuaJavaBridge.releaseLuaFunction(luaFuncCallback);
}
});