首先用 cocos code ide 编写lua 代码
用 adt 编写 java 代码,只要修改了java代码,就必须用adt重新部署一次,再用ide运行runtime就有效果,否则看不到修改java代码后的效果,而且如果修改了方法,会因为找不到方法导致程序崩溃
Lua 调用 java
Java方法中的所有参数必须加final关键字如:
public static Stringtest1(final String msg,finalint num){
Log.e("test1"," --- msg="+msg+" ,num= "+num);
return new String("I am Android");
}
lua中得代码
-- lua调用java
local function testLuaj()
local args = { "I am Lua" , 3455 } --传进java方法的参数
local signs = "(Ljava/lang/String;I)Ljava/lang/String;"--方法参数返回值类型
local luaj = require "luaj" --获取lua虚拟机
local className = "org/cocos2dx/lua/AppActivity"--类名
local methodName = "test1" --方法名
local ok , ret = luaj.callStaticMethod(className ,methodName,args ,
signs)
-- ok :是否调用成功, ret :调用成功后java的返回值
if not ok then
print("luajerror:",ret)
else
print("Thereturn value = "..ret)
end
end
Java 调用 lua
Lua 中的代码
local function callbackLua(param)
if "success"== param then
print("javacall back success")
end
end
args= { "callbacklua",callbackLua }
sigs= "(Ljava/lang/String;I)V"
ok= luaj.callStaticMethod(className,"callbackLua",args,sigs)
if not ok then
print("callcallback error")
end
java中的代码
public static void callbackLua(final String tipInfo,finalint luaFunc){
Cocos2dxLuaJavaBridge.callLuaFunctionWithString(luaFunc,"success");
Cocos2dxLuaJavaBridge.releaseLuaFunction(luaFunc);
}
lua test里面的范例
lua中的代码
if (cc.PLATFORM_OS_ANDROID ==targetPlatform)
then
localargs = {
2 ,3}
localsigs =
"(II)I"
localluaj =
require "luaj"
localclassName =
"com/cocos2dx/sample/LuaJavaBridgeTest/LuaJavaBridgeTest"
localok,ret =
luaj.callStaticMethod(className,"addTwoNumbers",args,sigs)
if not ok then
print("luaj error:",ret)
else
print("The ret is:",ret)
end
local function callbackLua(param)
if"success"==
paramthen
print("java call back success")
end
end
args = { "callbacklua", callbackLua }
sigs = "(Ljava/lang/String;I)V"
ok = luaj.callStaticMethod(className,"callbackLua",args,sigs)
if not ok then
print("call callback error")
end
end
java中的代码
public static int addTwoNumbers(finalint num1,finalint
num2){
return num1 + num2;
}
public static void callbackLua(final String tipInfo,finalint luaFunc){
//这里调用的时lua中得局部函数,通过lua传过来的luaFunc为标示找到对应的局部函数
Cocos2dxLuaJavaBridge.callLuaFunctionWithString(luaFunc,"success");
Cocos2dxLuaJavaBridge.releaseLuaFunction(luaFunc);
}
java主动调lua,functionName为lua中得全局函数,不能有local关键字
Cocos2dxLuaJavaBridge.callGlobalLuaFunctionWithString("functionName","success");