尝试使用事件侦听器时发生索引错误

时间:2017-05-23 17:19:03

标签: events lua corona

我正在尝试向正在加载的图像对象添加触摸事件侦听器。虽然这实际上是文档中的精确复制和粘贴: https://docs.coronalabs.com/api/type/EventDispatcher/addEventListener.html

它返回以下错误:

36:尝试索引本地'对象' (零值)

local t = {}
local img = {}
local i = 1

local function showImages ()
    local function networkListenerImg( event )
        if ( event.isError ) then
            print ( "Network error - download failed" )
        else
            event.target.alpha = 0
            transition.to( event.target, { alpha = 1.0 } )
        end
    end

    for k,v in pairs(t) do
        img[#img + 1] = v
    end

    local object = display.loadRemoteImage( event.params.chapter .. img[i], "GET", networkListenerImg, img[i], system.TemporaryDirectory, 50, 50 )

    function object:touch( event )
        if event.phase == "began" then
            print( "You touched the object!" )
            return true
        end
    end

    object:addEventListener( "touch", object )

end

表t填充在代码的其他位置并正确填充。

1 个答案:

答案 0 :(得分:2)

虽然你没有提到哪一行是第36行(那里只有28行),我仍然可以看到你的错误。问题是object始终为nildisplay.loadRemoteImage()不会返回任何内容,请参阅this

您需要做的是让您的侦听器回调捕获object,必须在回调之前声明。然后,回调应将object的值设置为下载结果。像这样......

local t = {}
local img = {}
local i = 1

local function showImages ()

    local object
    local function networkListenerImg( event )
        if ( event.isError ) then
            print ( "Network error - download failed" )
        else
            event.target.alpha = 0
            transition.to( event.target, { alpha = 1.0 } )
            -- fill in code to save the download object into "object"
        end
    end

    for k,v in pairs(t) do
        img[#img + 1] = v
    end

    display.loadRemoteImage( event.params.chapter .. img[i], "GET", networkListenerImg, img[i], system.TemporaryDirectory, 50, 50 )

    function object:touch( event )
        if event.phase == "began" then
            print( "You touched the object!" )
            return true
        end
    end

    object:addEventListener( "touch", object )

end