Skip to content

Instantly share code, notes, and snippets.

@PhilipWitte
Created September 3, 2014 18:46
Show Gist options
  • Save PhilipWitte/0e9d9a990f295a9415c4 to your computer and use it in GitHub Desktop.
Save PhilipWitte/0e9d9a990f295a9415c4 to your computer and use it in GitHub Desktop.
Event System
import StrUtils
# ---
type Foo =
ref object
value: int
type Bar =
ref object
value: char
proc update(f:Foo) = echo f.value
proc update(b:Bar) = stdout.write(b.value)
# ---
proc updateItems[T]: var seq[T] {.inline noInit.} =
var items{.global.}: seq[T] = @[]
return items
proc updateAll[T] =
for i in updateItems[T]():
update(i)
# ---
var updates: seq[proc(){.nimcall.}] = @[]
proc setup =
# add instances
updateItems[Foo]().add(Foo(value:256))
updateItems[Bar]().add(Bar(value:'h'))
updateItems[Bar]().add(Bar(value:'i'))
updateItems[Bar]().add(Bar(value:' '))
# add events
updates.add(updateAll[Foo])
updates.add(updateAll[Bar])
# print help message
echo "type 'exit' to quit"
echo "type 'exec' to execute all updates"
echo "type 'foo <int>' to add a new Foo"
echo "type 'bar <char>' to add a new Bar"
proc run =
while true:
var line = readline(stdin)
if line.len >= 4:
case line[0..3]:
of "foo ":
updateItems[Foo]().add(Foo(value:parseInt(line[4..line.high])))
of "bar ":
updateItems[Bar]().add(Bar(value:line[4]))
of "exec":
for u in updates: u()
echo ""
of "exit":
break
else:
echo "Please entry a valid command"
# ---
when isMainModule:
setup()
run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment