wolfhacklua API 1.1 Forum

Timing and animation

The clocks#

FunctionMeaning
time.now()Seconds since this script loaded. Advances with drawn frames.
time.dt()Seconds the last frame took. Also passed to frame handlers.
time.frame()The frame number since load.
time.wall()Unix time, for the real clock: os.date("%H:%M", time.wall()).
os.clock()CPU time of the process; use it to measure how long your own code takes.

time.now() and time.dt() only advance while the overlay draws frames. The overlay is idle when nothing draws, so do not use them to measure real elapsed time over a long pause; use time.wall().

Frame-rate independence#

Frames arrive at 60, 144 or 240 per second depending on the player's setup. Anything that moves or counts down must be scaled by dt, or it will run faster on a faster machine:

lua
local x = 0
events.on("frame", function(dt)
  x = x + 100 * dt            -- 100 pixels per second, at any frame rate
end)

anim.approach(current, target, rate, dt) is the frame-rate independent way to make a value follow a target smoothly:

lua
local shown = 0
events.on("draw", function()
  shown = anim.approach(shown, store.get("on", false) and 1 or 0, 12, time.dt())
end)

Timers#

lua
timer.after(2, function() log.info("once, two seconds from now") end)
local id = timer.every(10, function() store.save() end)     -- every 10 seconds
timer.cancel(id)

timer.every accepts at least 0.02 seconds. Timers run on the script's own clock inside the frame budget, so a timer is late rather than early when the overlay is busy. At most 64 per script.

Tasks: waiting without callbacks#

A task is a coroutine the host resumes. task.wait(seconds) pauses it, task.yield(frames) skips frames, and task.await(handle) waits for a request, a texture or a scan:

lua
task.spawn(function()
  local tex = assets.texture("assets/logo.png")
  task.await(tex)                       -- waits until it is decoded
  log.info("logo is " .. tex:size() .. " px wide")
end)

Tasks are the tidy way to write "do this, wait, do that". They only work inside task.spawn.

Tweens, easing and springs#

  • anim.ease(name, t) turns progress 0..1 into a curve; the names are in anim.names.
  • anim.tween{ from, to, duration, ease, delay, loop, on_update, on_done } animates a number over time; read tw.value.
  • anim.spring(initial, { stiffness, damping }) chases a target with natural overshoot; set it with sp:target(v).
lua
local tw = anim.tween{ from = 0, to = 1, duration = 0.5, ease = "out_cubic" }
events.on("draw", function()
  draw.rect(20, 20, 200 * tw.value, 10, 0xFFFFFFFF)
end)

Tweens and springs are advanced by the host every frame and are removed when the script stops.

API 1.1 · source docs-src/pages/guide/timing.md