Skip to content

Instantly share code, notes, and snippets.

@PhilipWitte
Last active January 28, 2021 10:49
Show Gist options
  • Save PhilipWitte/31b32858e23604bd925e to your computer and use it in GitHub Desktop.
Save PhilipWitte/31b32858e23604bd925e to your computer and use it in GitHub Desktop.
Nim Composition Concept
# Inheritance implies runtime memory overhead, so using it for small things like Particles
# is not ideal even though inheritance (to a Sprite base-type for instance) might be useful.
# We could 'auto compose' types instead as a way to use limited inheritance without it's costs
type
Sprite = object
resource: Image
position: Vector
rotation: Vector
Placeable = concept s
s.position is Vector
s.rotation is Vector
type
Ship = object as Sprite # note the 'as' keyword
health: float
strength: float
proc move(s:var Sprite, v:Vector) =
# operates on Sprite data
s.position += v * Time.delta
proc update(s:var Ship) =
# operates on Ship data
s.health -= 0.01
s.position += Vector.up(0.1) # Ship has a position!
let xwing = Ship(...)
xwing.update()
xwing.move(...) # works!
assert xwing of Sprite # false
assert xwing is Sprite # false
assert xwing as Sprite # true
assert xwing is Placeable # true
# Taking this further, it would theoretically be possible to have multi-pseudo-inheritance
type
A = object
B = object
C = object as A, B
proc foo(a:A) = echo "A"
proc foo(b:B) = echo "B"
proc foo(c:C) = echo "C"
let c = C()
foo(c) # prints 'C'
foo(c as A) # prints 'A'
foo(c as B) # prints 'B'
# And of course we could combined both inheritance and composition together
type
XWing = object of RebelUnit as Sprite, RigidBody
health: float
torpedos: int
wingsOpen: bool
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment