修订 版本 2024.3703 关键词 CoronaCards,Android 另请参阅 项目集成 — Android
Lua 和 Java 环境之间的通信是通过 CoronaView 实例完成的,该实例允许在两个环境之间发送**事件**。
在 Java 中,这些事件由 Hashtable
实例表示。在 Lua 中,它们是基本的 Lua 表。两者都遵循 Corona 的事件约定,使用必需的 "name"
键及其字符串值来标识键。其他信息可以通过一系列
两个环境之间事件的中心路由器是 Lua 端的全局 Runtime 对象。
您可以通过构建 Corona 样式的事件将事件从 Java 发送到 Lua。在下面的示例中,我们通过实例化 HashMap
的实例来创建一个自定义事件类型 ("pauseEvent"
)。我们使用正确的字段(键/值对 "name"
/"pauseEvent"
)和自定义字段 "otherKey"
/"otherValue"
填充它。然后我们调用 CoronaView 方法 sendEvent
,传入 Hashtable
。CoronaView 将自动将其转换为 Lua 表并将其分派给任何已向全局 Runtime 对象注册的 Lua 监听器。
// [Java] CoronaView view = ... Hashtable<Object, Object> event = new Hashtable<Object, Object>(); event.put("otherKey", "otherValue"); event.put("name", "pauseEvent"); view.sendEvent(event);
-- [Lua] local function handlePause( event ) if ( event.phase == "pause" ) then print( event.name ) --> pauseEvent print( event.otherKey ) --> otherValue --handle pause implementation here end return true end Runtime:addEventListener( "pauseEvent", handlePause )
CoronaView 实例中的 Lua 代码可以向 CoronaView
发送事件。这些事件的类型应为 coronaView
,并且您必须使用 setCoronaEventListener
注册一个 CoronaEventListener
来监听它们。在调用监听器时,Lua event
表将被转换为 Hashtable
。
// [Java] coronaView.setCoronaEventListener(new CoronaEventListener() { @Override public Object onReceivedCoronaEvent(CoronaView view, Hashtable<Object, Object> event) { android.util.Log.i("Corona", event.get("message")); return "Nice to meet you CoronaCards!"; } });
-- [Lua] local function pressMe( event ) if ( event.phase == "ended" ) then local event = { name="coronaView", message="Hello from CoronaCards!" } -- Dispatch the event to the global Runtime object local result = Runtime:dispatchEvent( event ) print( "Response: " .. result ) --> Response: Nice to meet you CoronaCards! end return true end local myObject:addEventListener( "touch", pressMe )