attempt to index global 'self' (a nil value)

天大地大妈咪最大 提交于 2019-12-13 09:49:44

问题


This is part of my game.lua I keep getting this error though.

function scene:createScene(event)

end

screenGroup = self.view

background = display.newImage("Space-Background-Image.gif")
screenGroup:insert(background)

local background1 = display.newImage("Space-Background-Image.gif")
background.x = 90
screenGroup:insert(background1)


function scrollBackground(self,event)
if self.x < -480 then   
    self.x = 480
else
    self.x = self.x - 3
end
end

回答1:


It appears to me that you've misplaced the closing end in your createScene method. Try moving the lines below into the function body so the implicit self is used instead of the global self key:

function scene:createScene(event)
  screenGroup = self.view

  background = display.newImage("Space-Background-Image.gif")
  screenGroup:insert(background)

  local background1 = display.newImage("Space-Background-Image.gif")
  background.x = 90
  screenGroup:insert(background1)
end



回答2:


There are two ways to call functions in lua

1) call the function with ':' gives 'm' as first argument m:DoJob()

2) but if you call if with '.' you have to define the context where to look for the function, typically the module itself m.DoJob(m)

If you call a method defined in the module as module:Method() with module.Method() it expects as argument self and throws an error.



来源:https://stackoverflow.com/questions/20258484/attempt-to-index-global-self-a-nil-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!