Can a timer callback be inside a sprite? (self:function)

First of all, I'm new to Lua and I haven't coded since the early 2000's so even though the answer might be plainly written in the documentation, it goes over my head.

I like to try and keep things separated as different sprites but now I've run into an issue where I want a timer callback to deal with sprite specific variables, self.value so I would like the callback to target the specific instance of a sprite.

I can't get it to work. Is it even possible? If so how? In the example below I want the Clock:moveHand to be the callback for a timer that is created by the same sprite.

function Clock:moveHand()
    self.time += 1
    self:drawTime()
    self:somethingElse()
end

function Clock:turnOn()
    if not self.clockIsTicking then
        pd.resetElapsedTime()
        self.clockTimer = pd.timer.new(100, self:moveHand)
        self.clockTImer.repeats = true
        self.clockIsTicking = true
    end
end

self.clockTimer = pd.timer.new(100, self.moveHand, self) should do it.

Any arguments passed to timer.new after the callback get passed to the callback, and in Lua, passing the instance of an object as the first argument is the same as calling a method with : on that instance.

So with the above line, when the timer finishes it will call self.moveHand(self), which is equivalent to self:moveHand()

3 Likes

Thanks, will try it whenever I get a spare moment to work on my game.
Much appreciated.

Tested it, and it worked! Thanks so much.

1 Like

Well, I learned something new here! My approach to this was far less elegant. I was creating a closure by storing a reference to self in a local variable, and then referencing that in an anonymous function, as in:

local s = self
self.clockTimer = pd.timer.new(100, function()
    s:moveHand()
end)