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]
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)
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() # <----
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?
Thanks. That worked. The compiler told me to use {.base.} too.
Should I use method on all procs that are specific to types, though?
I switched them all to method, but then the compiler told me to use {.base.} on all of them, but some procs aren't supposed to have a base method in Widget, as they are specific to the sub-objects, like the proc set text(l:Label).
I'm getting some warning on some methods saying generic method not attachable to object type is deprecated
What does that mean?
Still not quite understanding it, but it did go away when I changed the style argument in
method set_style*(b:BaseButton, style:Table) {.base.} = assert(false, "BaseButton.set_style() to override.")
from Table to
method set_style*(b:BaseButton, style:Style) {.base.} = assert(false, "BaseButton.set_style() to override.")
a Style type I created for the button colors.
That method became redundant after the change anyway. :)