对于事件类型(event.type)感到困惑的Lua。

我正在学习方向的书籍,但是我对代码中的 event.type 非常困惑。

以下是书中的代码:

portrait = display.newText("Portrait", display.contentWidth/2, display.contentHeight/2, nil, 20)
portrait:setFillColor(1, 1, 1)
portrait.alpha = 1

landscape = display.newText("Landscape", display.contentWidth/2, display.contentHeight/2, nil, 20)
landscape:setFillColor(1, 1, 1)
landscape.alpha = 0

local function onOrientationChange(event)
    if (event.type == "landscapeRight" or event.type == "landscapeLeft") then
        local newAngle = landscape.rotation - event.delta
        transition.to(landscape, {time = 1500, rotation = newAngle})
        transition.to(portrait, {rotation = newAngle})
        portrait.alpha = 0
        landscape.alpha = 1
    else
        local newAngle = portrait.rotation - event.delta
        transition.to(portrait, {time = 150, rotation = newAngle})
        transition.to(landscape, {rotation = newAngle})
        portrait.alpha = 1
        landscape.alpha = 0
    end
end

整个方向更改函数似乎都是围绕着 event.type 进行的。我不理解它是什么,并且我也不明白它等于什么 (==)。当我更改它等于的字符串(在这种情况下是 'landscapeRight' 和 'landscapeLeft')时,它仍然可以接受任何值并且仍然可以正常运行。我完全没有弄明白它是如何工作的,请解释一下 event.type。

点赞
用户3080396
用户3080396

在 Lua 中,使用字符串如 'landscapeRight' 作为枚举字面量是一种常见的惯用法。

对于 orientation 事件,event.type 保存了新的设备方向。

在您提供的代码片段中,看起来您并没有调用或以其他方式参考定义后的 onOrientationChange。您应该使用以下方法将其附加到 Runtime 对象:

Runtime:addEventListener('orientation', onOrientationChange)
2014-02-11 00:53:39
用户869951
用户869951

希望你接受 MBlanc 的回答,我在这里稍微扩展一下:orientation 事件的 type 值是几个字符串中的一个,就像 MBlanc 的帖子中链接中所指示的那样。Event.type 永远不会是那些字符串之外的任何东西。因此,通过将比较更改为永远无法匹配 event.type 的字符串,你实际上是始终在进入 “else” 分支,就好像你的设备从未处于横屏状态:

local function onOrientationChange (event)
    if (event.type == 'blabla1' or event.type == 'blabla2')    then
        ...do stuff -- 但是永远不会运行,因为 event.type 永远不可能有那些值
    else -- 因此,你的程序始终会到达这里:
        ...do other stuff...
    end
end

这将使程序看起来一切正常,除了当你的设备真的处于横向右侧或左侧方向时,程序将执行 “else” 块而不是应该执行的块(第一个块)。

2014-02-11 17:56:11