[AGS 4] State of polymorphism in AGS 4?

Started by Monsieur OUXX, Yesterday at 22:10:05

Previous topic - Next topic

Monsieur OUXX

It's an open question.

I just want to know if there's some progress in the direction of polymorphism (whether be through casting or interfaces or whatnot).
- If yes, then please point me in the right direction (I did a search in the forums but couldn't find anything).
- If not, then don't waste time providing workarounds. It's OK, I know how to do it the hard way. I'm only asking if there's now an easy way ;)

===========

By polymorphism I mean this kind of scenarios (pseudo code) :

Code: ags
managed struct Parent {
    int Id;
};


managed struct Child extends Parent {
    String whatever;
};


Parent DoThingWithAnythingDerivedFromParent(Parent obj) {
    return obj;
}

void game_start() {
    Child child = new Child;
    Child child2 = (Child) DoThingWithAnythingDerivedFromParent(child);
}

 

Crimson Wizard

#1
There's a "user cheat sheet" for the new scripting features in AGS 4:
https://github.com/adventuregamestudio/ags/wiki/New-compiler%27s-end-user-cheat-sheet



The type casting is possible for managed types, in both ways.

1. Upcasting, child -> parent, was always possible, and is resolved at compile time.
2. Downcasting, parent -> child, is supported in AGS 4 using C#-like "X as Y" syntax, and is resolved at runtime:
Code: ags
Button* btn = control as Button;
MyChild* child = parent_ptr as MyChild;
This works with any managed struct, whether built-in, declared by user or from plugins (but plugins must register the types correctly for this to work, because it's based on checking typenames at runtime).
Downcasting does not throw any errors in case of failure, but returns "null" if pointer cannot be cast to the requested type. This is also useful if you iterate through an array of parent pointers, which may point to multiple child types, and check which actual child type each object is.



Method overriding is currently NOT possible, because there's no proper support for virtual function table. So you still cannot have separate implementations for the same function in parent and child structs.
This may be worked around somehow. For example, one could store a "my type id" in a parent class, or test which type the "this" pointer is, make a downcast, and delegate to particular child's function. That's just one idea, perhaps there may be other solutions.

Monsieur OUXX

Flawless answer. Thanks a lot!
(keep some time for yourself!!! No burnout please <3 )
 

SMF spam blocked by CleanTalk