2017-05-23 48 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

謝謝!這正是問題所在。 –

相關問題