Tweens and Callback

I am writing a program that relies on the callback function of the tween. The callback is being triggered right after the tween is run. Not after the 3 second duration delay which it is supposed to do.

What’s your tween code look like.

Hold on.

@dave1707

This is exactly what I did. Just the basics.

-- Use this function to perform your initial setup
function setup()
    tableuse = {x=0}
    tween(3.0,tableuse,{x=20},tween.easing.linear,print("done"))
end

-- This function gets called once every frame
function draw()
    background(0,0,0,255)
end

Here’s a tween that waits 3 seconds and has a lot of empty {}.

function setup()
    tween(3,{},{},{},function() print("done") end)
end

Or just a 3 second delay.

function setup()
    tween.delay(3,function() print("done") end)
end

You need a function for your callback, not code. The code will execute immediately.

Depending on the size of your callback function, you can have it inline like I show above. Or if the function would have a lot of code in it, you can make it a seperate function and put the function name as the callback.

function setup()
    tableuse = {x=0}
    tween(3.0,tableuse,{x=20},tween.easing.linear,done)
end

function done()
    print("done")
    -- a lot more code here
end

Oh I see. Okay, that would make sense then. Thank you so much @dave1707

Wrapping a function inside another function like you can do for callbacks for tween, parameter, http.request and so on is a feature of Lua (and some other languages) known as a closure. They’re pretty interesting things to read up on, if you google “Lua closure” there are some interesting articles on them.

A 3rd pattern is to define the callback as a local function:

function setup()
    local function callback() print("done") end --a callback closure
    tween.delay(3,callback)
end

Effectively it’s the same as the inline method @dave1707 mentioned above, but can be tidier if the callback is complex. This closure pattern is useful if you need to refer to local variables in the enclosing function, as the closure will remember them.