android平台代码和Lua代码的交互均通过C++和Java交互,Lua再和C++交互
C++和Java的交互,可以参考 (*)
下面直接看用法:
lua调用java
lua中使用 luaj.callStaticMethod 来调用java静态方法:
使用场景例如提交统计,提交游戏分数
-- launch app function JniUtil:callJavaBuyLife() local argsJson = nil local sigs = "()V" local luaj = require "cocos.cocos2d.luaj" local className = "org/cocos2dx/lua/AppActivity" local ok,ret = luaj.callStaticMethod(className,"pay",{argsJson},sigs) if not ok then print("==== luaj error ==== : ",ret) return false else print("==== The JNI return is:",ret) return ret end end
在AppActivity中,加入静态方法:
public static void pay() { // ... }
java调用lua
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
使用场景:例如我们在支付SDK中购买完了钻石后回调到游戏中
下面提供callLuaGlobalFunctionWithString用法:
function G_CallbackFromJava(msg) if msg == "success" then -- ... end end
Java中对这个全局函数直接调用他,如果G_CallbackFromJava里要涉及图形计算,需要启用OpenGL线程:
sInstance.runOnGLThread(new Runnable() { @Override public void run() { Cocos2dxLuaJavaBridge.callLuaGlobalFunctionWithString("G_CallbackFromJava","success"); } });
添加import语句:
import org.cocos2dx.lib.Cocos2dxLuaJavaBridge;
下面提供callLuaFunctionWithString用法:
function JniUtil:callJavaCallbackLua(func) local luaj = require "cocos.cocos2d.luaj" local className = "org/cocos2dx/lua/AppActivity" local args = { "callbacklua",func } local sigs = "(Ljava/lang/String;I)V" local ok = luaj.callStaticMethod(className,"callbackLua",args,sigs) if not ok then print("============= call callback error") else print("------------- call callback success") end end
local function onBack(msg) self:resumeGame() end JniUtil:getInstance():callJavaCallbackLua(onBack)
Java中可以直接回调这个函数,也可以先保存下来这个注册的Lua局部函数,一般都是保存下来,等待启用SDK充值逻辑走完后再回调
static int luaFuncCallback = 0; public static void callbackLua(final String tipInfo,final int luaFunc){ // 根据需要,看是否要retainLuaFunction luaFuncCallback = luaFunc; // tipInfo为Lua里传来的“callbacklua”这里没用 }
sInstance.runOnGLThread(new Runnable() { @Override public void run() { Cocos2dxLuaJavaBridge.callLuaFunctionWithString(luaFuncCallback,"success"); Cocos2dxLuaJavaBridge.releaseLuaFunction(luaFuncCallback); } });