2017-05-23 42 views
0

我正在尝试向正在加载的图像对象添加触摸事件侦听器。虽然这实际上是从文档的精确复制和粘贴: 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在代码中的其他位置填充并正确填充。

+0

确保'object'不是'nil'。另外,我没有在代码中看到'event.params.chapter'的声明。 – ldurniat

+0

Event.params.chapter是从前一场景传递的值。 –

回答

2

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

您需要做的是让您的侦听器回调捕获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 
+0

谢谢!这正是问题所在。 –

相关问题