I'm making a few ui widgets for a terminal emulation thingy I'm doing (for a
roguelike), and I'm trying to do some inheritance. But I'm having a bit of a
problem.
So far I got what you see in the code right below: a Widget base class, a Label
sub-object of Widget, and a Ui object that creates and stores all the widgets
and the consoles (which are where the widgets get drawn to -- basically
individual terminals).
type
Widget* = ref object of RootObj
id:int
x:int
y:int
console:Console
# ... etc
Label* = ref object of Widget
text:string
length:int
Ui* = ref object
consoles*:seq[Console]
widgets*:seq[Widget]
Run
And each Widget subobject will have its own draw procedure, and I made one for
the label like so:
proc draw(l:Label) =
l.console.print(l.x, l.y, l.text)
Run
Now comes my problem: the widgets sequence in the `ui` object is a sequence of
`Widget` objects, and when I update things, it doesn't seem to recognize the
subobject type on its own. I had to do this:
proc update*(ui:Ui) =
for w in ui.widgets:
if w of Label: # <----
Label(w).draw() # <----
Run
That works. But doing that way means that I'll need a whole bunch of checks to
find out the type of each widget in ui.widgets when I have many types of
widgets, and that will become unwieldy when I have more function needing to
iterate through the widgets.
Is there a way to do this without having to check for the type of the object?