CoronaCards — iOS

Native/Lua 通信

此时,Lua 和 iOS 环境之间的通信通过Obj-C层来完成。为了简化此流程,CoronaView 实例允许从一个环境发送事件到另一个环境。

在 Obj-C 中,这些事件由 NSDictionary 实例表示。在 Lua 中,它们是基本的 Lua 表。两者都遵循 Corona 对具有必需 "name" 的事件的约定,该事件会产生一个用于识别 key 的字符串值。此外,还可以通过一系列键值对另外传递更多信息。

Obj-C 到 Lua

在 Obj-C 方面,可以通过构建Corona 样式事件向 CoronaView 实例发送事件。例如,如果你有一个应该在 CoronaView 实例内触发事件的 UIButton,那么可以创建一个新的 NSDictionary 实例,为其填充你要传递的信息,然后发送事件。在 Lua 部分,CoronaView 会将此 NSDictionary 对象转换为 Lua 表,并将其分派给注册为侦听该事件的任何 Lua Runtime 侦听器。

以下示例说明了在Obj-C和 Lua 方面此概念

// [Obj-C]
CoronaView *view = ...
NSDictionary *event = [NSDictionary dictionaryWithObjectsAndKeys:
    @"pauseEvent", @"name",
    @"pause", @"phase",
    @"otherValue", @"otherKey",
    nil];
[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 )

Lua 到 Obj-C

CoronaView 实例中的 Lua 代码可以向 CoronaView 发送事件。这些事件应为 coronaView 类型,你必须注册一个 CoronaViewDelegate(附加到 CoronaView)以侦听它们。在这种情况下,Lua event 表在被委托接收时会转换为 NSDictionary

以下示例说明了在Obj-C和 Lua 方面此概念

// [Obj-C]
// Change the value of the UILabel element 'myLabel'
- (id)coronaView:(CoronaView *)view receiveEvent:(NSDictionary *)event
{
    NSLog( @"Logging properties of the event: %@", event );
    self.myLabel.text = [event objectForKey:@"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

myObject:addEventListener( "touch", pressMe )

Lua 模块

桥接Obj-C和 Lua 世界的稍微低级别的办法是创建一个 Lua 模块。这需要使用 Lua C API,它能让你从 C 中调用 Lua 代码,并为 C 代码创建可以在 Lua 中调用的封装器。