Skip to content

Instantly share code, notes, and snippets.

@exelotl
Last active September 13, 2018 22:00
Show Gist options
  • Save exelotl/e1b68d957bc4bdf4008b716341fe163a to your computer and use it in GitHub Desktop.
Save exelotl/e1b68d957bc4bdf4008b716341fe163a to your computer and use it in GitHub Desktop.
nim dynamic dispatch test
import strformat
type Entity = ref object of RootObj
tid: int # tid uniquely identifies which subclass we are (e.g. Foo or Bar)
type Foo = ref object of Entity
x, y: float
name: string
type Bar = ref object of Entity
health: int
name: string
# constructors
proc newFoo(name:string):Foo = Foo(tid:0, name:name, x:5, y:6)
proc newBar(name:string):Bar = Bar(tid:1, name:name, health:100)
# each type has a different update method
proc updateFoo(self:Foo) = echo "Hello from Foo {self.name} ({self.x},{self.y})".fmt
proc updateBar(self:Bar) = echo "Hello from Bar {self.name} ({self.health} hp)".fmt
type EntityFn = proc(e:Entity){.nimcall.}
# this allows you to look up the relevant 'update' procedure for a given type (based on tid)
const updateTbl:array[2, EntityFn] = [
cast[EntityFn](updateFoo),
cast[EntityFn](updateBar)
]
let entities = @[newFoo("fred"), newBar("bob")]
for e in entities:
let update = updateTbl[e.tid] # get the correct procedure for this type of entity
update(e)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment