Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- require "socket"
- local start_time = socket.gettime() * 1000
- local timeouts = {}
- local intervals = {}
- local function step()
- -- calculate frame rate and delta
- local now = socket.gettime() * 1000
- local delta = (now - start_time) + 0.02
- start_time = now
- -- and process intervals and timeouts
- for i, v in ipairs(timeouts) do
- v.time = v.time - delta
- if v.time <= 0 then
- v.func(v.args)
- table.remove(timeouts, i)
- end
- end
- for i, v in ipairs(intervals) do
- v.time = v.time - delta
- if v.time <= 0 then
- v.func(v.args)
- v.time = v.start
- end
- end
- end
- -- Add a function to be called after x milliseconds.
- -- Returns the id of the binding.
- local function setTimeout(func, time, ...)
- d = {}
- d.func = func
- d.time = time
- d.args = ...
- table.insert(timeouts, d)
- return #timeouts
- end
- -- Add a function to be called every x milliseconds.
- -- Returns the id of the binding.
- local function setInterval(func, time, ...)
- d = {}
- d.func = func
- d.time = time
- d.start = time
- d.args = ...
- table.insert(intervals, d)
- return #intervals
- end
- -- Remove a function from being called.
- -- Takes the function or the bindings id as the first argument.
- -- If a function is given, you can pass the maximal number of bindings to be
- -- removed as the second argument.
- local function clearTimeout(id, n)
- if type(id) == "number" then
- if id > 0 and id <= #timeouts then
- table.remove(timeouts, id)
- return true
- else
- return false
- end
- else
- local ret = 0
- local n = n or 1
- for i, v in ipairs(timeouts) do
- if v == id then
- table.remove(timeouts, i)
- ret = ret + 1
- if ret >= n then
- return ret
- end
- end
- end
- return 0
- end
- end
- -- Like clearTimeout but with intervals :P
- local function clearInterval(id)
- if type(id) == "number" then
- if id > 0 and id <= #intervals then
- table.remove(intervals, id)
- return true
- else
- return false
- end
- else
- local ret = 0
- local n = n or 1
- for i, v in ipairs(intervals) do
- if v == id then
- table.remove(intervals, i)
- ret = ret + 1
- if ret >= n then
- return ret
- end
- end
- end
- return 0
- end
- end
- -- EXAMPLE
- tpt.register_step(step)
- -- Count to three in 3 seconds
- local n = 1
- setInterval(function()
- print(n)
- n = n + 1
- if n > 3 then
- clearInterval(#intervals) -- clear the last one
- end
- end, 1000)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement