Last active
December 25, 2015 04:19
-
-
Save usysrc/6916653 to your computer and use it in GitHub Desktop.
code scetch and not very fast
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| --[[ | |
| Temporal Recursion in Lua | |
| headchant 2013 | |
| follwing: http://extempore.moso.com.au/temporal_recursion.html | |
| tested with luajit: stable 2.0.2 | |
| --]] | |
| --[[ | |
| 88 MP/H, fixed timestep | |
| --]] | |
| local callbacks = {} | |
| local t = 0 | |
| local now = function() return t + 1 end | |
| function run() | |
| t = t + 1 | |
| if callbacks[t] then | |
| callbacks[t]() | |
| end | |
| -- delete the past, save memory | |
| if t > 0 then | |
| callbacks[t-1] = nil | |
| end | |
| end | |
| callback = function(t, f) | |
| if callbacks[t] then | |
| local g = callbacks[t] | |
| callbacks[t] = function() | |
| g() | |
| f() | |
| end | |
| else | |
| callbacks[t] = f | |
| end | |
| end | |
| --[[ | |
| SUGAR: | |
| --]] | |
| local closure = function(f) | |
| local g | |
| g = function() | |
| f(g) | |
| end | |
| return g | |
| end | |
| local closurecall = function(f) | |
| closure(f)() | |
| end | |
| function len(f, dur) | |
| local s = t | |
| local fun | |
| fun = function() | |
| if t < s + dur then | |
| f() | |
| callback(now(), fun) | |
| end | |
| end | |
| fun() | |
| end | |
| sched = function(f, when, dur) | |
| callback(when, function() len(f, dur) end) | |
| end | |
| --[[ | |
| EXAMPLES | |
| --]] | |
| -- recursion | |
| function recursion() | |
| local f | |
| f = function(i) | |
| print(i) | |
| if i < 5 then | |
| f(i+1) | |
| end | |
| end | |
| f(0) | |
| end | |
| -- temporal recursion | |
| function temporal_recursion() | |
| local f | |
| f = function(i) | |
| print(i) | |
| if i < 5 then | |
| callback(now(), function() f(i+1) end) | |
| end | |
| end | |
| f(0) | |
| end | |
| -- concurrency | |
| function concurrency() | |
| closure(function(this) | |
| print(t,"FOO") | |
| callback(now(), this) | |
| end)() | |
| closure(function(this) | |
| print(t,"BAR") | |
| callback(now(), this) | |
| end)() | |
| end | |
| -- shared state / encapsulation | |
| function sharedstate() | |
| (function() | |
| local count = 0 | |
| closure(function(this) | |
| print("FOO", count) | |
| callback(now(), this) | |
| end)() | |
| closure(function(this) | |
| if count < 5 then | |
| count = count + 1 | |
| end | |
| callback(now(), this) | |
| end)() | |
| end)() | |
| end | |
| --[[ | |
| TESTS: | |
| uncomment one at the time, | |
| --]] | |
| -- recursion() | |
| temporal_recursion() | |
| -- concurrency() | |
| -- sharedstate() | |
| -- start the clock | |
| while true do | |
| run() | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment