Skip to content

Instantly share code, notes, and snippets.

@catfact
Created December 8, 2020 01:29
Show Gist options
  • Save catfact/614fcea7bd1c6d1fe1cbdd57b4211580 to your computer and use it in GitHub Desktop.
Save catfact/614fcea7bd1c6d1fe1cbdd57b4211580 to your computer and use it in GitHub Desktop.
softclock - mockup of soft-timer system in lua
-- module for creating collections of soft-timers based on a single fast "superclock"
-- this is a simple singleton implementation for test/mockup
-- TODO: allow multiple instances
-- TODO: allow changing the superclock period
local softclock = {}
-- this field represents the period of the superclock, in seconds
softclock.super_period = 1/128
softclock.clocks = {}
-- call this from the superclock
softclock.tick = function()
for id,clock in pairs(softclock.clocks) do
clock.phase_ticks = clock.phase_ticks + 1
-- asumption: subclock period is > 1 tick
if clock.phase_ticks > clock.period_ticks then
-- save the remainder
-- (this might need to be a while-loop to catch edge cases?)
clock.phase_ticks = clock.phase_ticks - clock.period_ticks
-- and fire the event
-- (maybe it is useful for the event to get the fractional phase, IDK)
clock.event(clock.phase_ticks)
end
end
end
softclock.add = function(id, period, event)
local c = {} -- new subclock table
c.phase_ticks = 0
-- convert argument from seconds to superclock ticks
c.period_ticks = period / softclock.super_period
print('adding clock; id ='..id..'; period_ticks='..c.period_ticks)
c.event = event
softclock.clocks[id] = c
end
softclock.remove = function(id)
-- TODO
end
softclock.clear = function()
-- TODO
end
return softclock
--- test of softclock module
local softclock = include('lib/softclock')
local function super_tick()
softclock.tick()
end
function init()
super_period = 1/8
super_metro = metro.init({time =super_period, event=super_tick})
softclock.super_period = super_period
softclock.add('a', 1/4, function(phase) print("a:"..phase) end)
softclock.add('b', 3/4, function(phase) print("b:"..phase) end)
softclock.add('c', 11/17, function(phase) print("c:"..phase) end)
super_metro:start()
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment