开发者

variable scope when dealing with event handlers

开发者 https://www.devze.com 2023-04-04 01:29 出处:网络
function World:draw() --draw the tiles based on 2d int开发者_C百科 array --draw the player --draw the monsters
function World:draw()
    --draw the tiles based on 2d int开发者_C百科 array
    --draw the player
    --draw the monsters
    --show what you need to based on camera
    self.map[0][0]=display.newImage("dirt_tile.png",i,j)
end

I can't access any of my world object's properties in there when I use the event handler:

Runtime:addEventListener("enterFrame",World.draw)

Is there a different kind of eventListener I can use, or is there a different way to instantiate the eventListener so the self-referencing context stays intact?


Here you go:

World = { count=0 }

function World:enterFrame()
    self.count = self.count + 1
    print("count = " .. self.count)
end

Runtime:addEventListener("enterFrame", World)

See this API reference page for details.


In you named your table local self = {}, then it may collide with the implicit self parameter.

The function World:draw() is just a Lua syntax sugar for World.draw = function(self). By working with self, you are using whatever first parameter the runtime event handler is passing to your function (judging from the API, it passes event, which you will get as self).

Try naming the table you want to access differently (like local this) and see if it works.

0

精彩评论

暂无评论...
验证码 换一张
取 消