Quick – Cocos2D-X Learning Series 10 LuA calls JAVA
Lua scripts are powerful, but without the flexibility and convenience to call JAVA will inevitably be inadequate. Many programming languages themselves will involve the interaction with other languages. I remember the interaction between C and M language in MATLAB a long time ago, and now I often design SHELL, PYTHON, C and other miscellaneous works. Let’s take a peek at the calls between LUA and JAVA.
Code 1.
The code is as follows:
local btn
btn = cc.ui.UIPushButton.new()
:setButtonLabel(cc.ui.UILabel.new({text= “call Java – showAlertDialog()”, size = 64}))
:onButtonClicked(function()
if device.platform ~= “android” then
— print(“please run this on android device”)
btn:setButtonLabel(cc.ui.UILabel.new({text= “please run this on androiddevice”, size = 32}))
return
end
— call Java method
local javaClassName = “org/cocos2dx/lua/AppActivity”
local javaMethodName = “showAlertDialog”
local javaParams = {
“How are you ?” .
“I’m great !” .
function(event)
local str = “Java method callback value is [” .. event .. “]”
btn:setButtonLabel(cc.ui.UILabel.new({text= str, size = 32}))
end
}
local javaMethodSig = “(Ljava/lang/String; Ljava/lang/String; I)V”
luaj.callStaticMethod(javaClassName, javaMethodName, javaParams, javaMethodSig)
end)
:align(display.CENTER, display.cx,display.cy)
:addTo(self)
btn:setKeypadEnabled(true)
btn:addNodeEventListener(cc.KEYPAD_EVENT, function (event)
dump(event)
local str = “event.keyis [ ” .. event.key .. ” ]”
btn:setButtonLabel(cc.ui.UILabel.new({text= str, size = 32}))
if event.key == “back” then
–print(“back”)
cc.Director:getInstance():endToLua()
if device.platform == “windows” or device.platform == “mac” then
os.exit()
end
elseif event.key == “menu” then
–print(“menu”)
end
end)
2. Code interpretation
Create a BUTTON and press it based on whether it is running on Android.
If you are using ANDROID, set the path to the Java class file, the method to be called, and the method parameters to be called.
Also set keyboard input touch ENABLE and create a touch listener. Determine the input letter and exit the program if it is back. But this code doesn’t work.)
When running on a real machine, press, press the touch screen will pop up a dialog box, is by the org/cocos2dx/lua/AppActivity function in a Java file.
To complete.
The key calling function is luaj. callStaticMethod.