-
-
Notifications
You must be signed in to change notification settings - Fork 21.3k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add Trait System to GDScript #97657
base: master
Are you sure you want to change the base?
Add Trait System to GDScript #97657
Conversation
Is there a specific reason you specified a If not, might I recommend a different return type for clarity? |
(Edited because I missed a part in the OP description) Fantastic start on this feature. Thank you! One comment: please use |
I'm not sure your reasoning lines up with your conclusion there, but I can't say I have much of a preference, what with it being a strictly cosmetic affair. |
This system seems very similar to the |
Abstract classes are still beholden to the class hierarchy: No class can inherit from two classes at a time. There is some value in having both of these, I suppose, but traits are far more powerful. |
See: Also, as DaloLorn said, these are independent features that can coexist together. Traits offer capabilities that classic inheritance cannot provide. |
This looks great, will traits be able to constrain typed collections (ie. Array[Punchable], Dictionary[String, Kickable]) ? |
Amazing that somebody cared to make this,but since the original proposal is shut down,here is some feedback
|
Considering work has already been made for signals, we should get to keep them too. (unless massive performance issues appear) |
I am a bit concerned on the performance of this in general, but that would be something that can be solved over time. I am really, really ecstatic about this. I agree. There's no reason to exclude signals from traits if the work has been done. |
36d7605
to
4088f53
Compare
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Just some nitpicks, mostly you should rename uses
with impl
everywhere.
As various others have suggested to use
The 6 characters
|
what would you abbreviate
Pretty sure non-native speakers are able to understand abbreviations, by your logic
traits aren't exactly beginner stuff, when someone starts with a language they learn they might learn traits ,but for gamedev you don't learn certain stuff until you get the basics/become a casual programmer , when i was a unity developer, i didn't learn about interfaces (which are extremely similar to traits) until i had advanced enough and realised i need some other solution to inheritance
this makes no sense? let's take a look at some example code: class_name Door
extends AnimatableBody3D
impl Interactable what would "implies" mean in a progammer context?, "impels" isn't even abbreviated correctly, "implant"? seriously?, "implode" would be a function for gameplay
previous points still matter, also rust uses the |
Is using a separate file extension necessary? And if not, would it be better to stick to .gd? From a UX perspective it seems a lot simpler and easier not to. |
Extensions can be useful for quick search, filter, etc., without the need to check the content of the file nor adding extra prefix/suffix to file names (so it's better in UX terms), also can help other tools like the filesystem to implement custom icons. |
Put me down as another vote in favor of "implements", for what it's worth. I'm indifferent on "implements" versus "uses", but I'm not nearly so indifferent on "impl" versus "implements": The majority of Adriaan's concerns have not been addressed to my satisfaction. |
I think |
I agree on "impl" been a very confusing keyword. |
To resolve the class reference error: Compile godot, then run |
f27a5d9
to
8d2b91c
Compare
Radiant pointed out today that, according to the "System Implementation Progress" checklist, tests and documentation have yet to be done. Is this something that other contributors could help with to move the PR along, or is it best left to the original authors of the PR? |
Documentation-wise, there isn't much to be done. The new |
Do user guides and tutorials fall outside of the scope of "documentation" for the purposes of this PR? It sounds like most, if not all, of the syntax has at least been locked down, so perhaps we could work on producing manual pages that describe how and why to use traits, so they're ready for when traits themselves are merged? |
@Meorge any help will be good, I have written some tests but intend to include more while the documentation task actually refers to what will appear on the user manual |
I personally far far far prefer
On a personal level I dislike it because for whatever reason I tend to confuse the keywords I haven't heard anyone give an actual reason they prefer |
I'm wondering if conflict resolution between trait functions is still a feature as mentioned in the proposal? I don't see it listed above. Was it forgotten or was there a reason the community decided to remove the feature? Or maybe that's being saved for a later proposal? This is a wonderful start and I really appreciate it for what it is! I mention it because I felt like even the original proposal wasn't far enough and eventually a syntax for full explicit conflict resolution for variables as well as methods would be ideal. I feel like in an ideal world, Traits could be something shared in an asset marketplace and dropped into projects to add complex functionality. I'd even love it if there was a Trait Node in the future where you could also add child nodes that would be added to the scene like inherited classes. That way you could literally compose an entire scene by dragging and dropping Traits (gdt files) into the scene tree and linking exported trait variables together. All of this vision though is nearly impossible if Traits can't handle conflict resolution. I also see a future where large rewrites are required because two traits have one small conflict. I feel like it's a really important feature to eventually add. |
To me, "uses" doesn't sound like it would really be correct English. I don't think I've ever heard someone say in English that someone "uses" a trait; they "have" a trait, or they "are" a trait. If there is an enemy that you can shoot, we don't say that "the enemy uses shootable" (perhaps there's a better phrasing I'm missing right now?). It's a bit more correct (but admittedly verbose, as you said) to say "the enemy implements behavior when it is shot". I suppose the most natural English would be to say "the enemy is shootable", which would translate to
which, while even less verbose than To summarize my thoughts:
|
Multiple people used that exact verbiage on this very page. That was what I was trying to point out.
I feel like that's kind of what you're actually doing. It's not a true "includes", but you're importing methods and constants into a class from another file. @Meorge Thank you for your thoughts. Could you or anyone else comment on what attracts you to |
IIRC pascal/delphi uses I don't know if taking PHP as a reference is a good idea since this language is a stitchup of different languages with caveats here and there - and I'm talking from years of professional experience with PHP before I managed to escape webdev. I heard that it's getting cleaned up with recent version, but still I wouldn't refer to it as an example of good programming language design. The word From delphi docs, since you're refering to this language:
I know that traits aren't exactly interfaces, but they are closely related - they act like one if a trait contains only declarations of methods and no definitions of them. Interfaces in C# can also contain fn implementations, provided they only refer to public fields, which makes them kinda like traits. I understand though that the word is a bit nerdy and perhaps could be replaced with something more friendly. |
Please note that the pull request is not intended to discuss the design of the feature, only its implementation (we should unlock the proposal). As for |
The waters there have been heavily muddied with the concept of default implementations. While some languages still hold that an interface must be strictly abstract, there's a fair few in common use today - e.g. Java/Kotlin, C#, Swift, or Python - where interfaces or interface-like constructs are permitted to implement some of their methods. |
Regarding the keyword to use, I agree that might be better to discuss on the proposal page. For the progress that needs to be made for the actual feature to be merged, I'm not sure how much there would be to add to the class reference but I could see a lot of value in preparing the user manual over at godot-docs with sections on traits and how to use them. I'll have to familiarize myself with the trait system before trying to write docs on it, but it's something I'd be happy to do 🙂 |
The functionality described here is an interface, not traits. An analogy: An interface (what you have here) is taking something you own off your shelf and adding a new kind of plug or label to it for other stuff to use. I think a lot of folks coming from newer languages that have "full" traits (which allow things like implementing a trait for all possible types described by a generic) would be a bit confused seeing this. Apologies for not putting this on the proposal page, it is currently locked. |
I think arguing over implements vs uses is largely irrelevant, I think getting tied up in semantics is in part why we have taken so long on settling on an implementation. I personally don't care if its uses or implements, I just want interfaces. I am very happy that we will be allowing default implementations, as that allows is to simplify the implementation of many behaviours, allowing for extension where needed. I think "pure" interfaces would be way less useful, especially for the way I think about them. |
While I definitely agree with the sentiment, and I'm really looking forward to having this in GDScript ASAP too, I think we're at the point with this feature now where these are the kinds of conversations we need to have - we can't push them off much further. Once this gets into a release (especially a non-dev one), it'll be really hard to change the terminology, so we want to make sure we do it right now. Since the proposal has not been opened, one argument against class_name SignPost
extends Node2D
uses Attackable, Interactable # these are traits/interfaces that the class takes advantage of, NOT namespaces
imports DialogueTools # these are namespaces that the class imports I suppose from context here you could infer that "Attackable" isn't a namespace, and "DialogueTools" isn't a set of things for this class to use, but the semantic meaning of the two lines still feels fuzzier than it should be. C#, a language that is often discussed alongside GDScript, uses My current preference is class_name SignPost
extends Node2D
is Attackable, Interactable The big downside I see here is that it's already a keyword used in other contexts, but those contexts are pretty substantially different (part of an expression, has a left operand, etc) and semantically, they mean very similar things (membership/adherence to a class/trait/interface). |
I've started a branch of godot-docs for adding trait support/discussion to the relevant spots in the user manual 🙂 I'm going off of what's currently in the Aside from the discussion on the keyword for trait use, we'll need to decide on how traits fit into the GDScript style guide. I'm not sure if that would be a better discussion for this thread, or the PR on godot-docs. |
While working on the documentation, I found behavior with static variables in traits that seems like it might not make sense? With this trait and class: trait SomeTrait:
static var some_var: int = 0
class MyClass:
uses SomeTrait You cannot do print(MyClass.some_var) because print(SomeTrait.some_var) This is tricky IMO, because overall the behavior is consistent with how classes work. But I'm struggling to think of a use case where a static member of a trait itself would be necessary, and I feel like there could be plenty of use cases for classes that use particular traits inheriting their static members the same way their instances inherit non-static members. |
Another thing: we should probably have a template specifically for traits that doesn't include |
Nice catch, that was a bug. It is now fix and have write a test for it. trait SomeTrait:
static var some_static_var = 0
static var other_static_var = 0
static var third_static_var = 0
static func some_static_func():
print("some static func")
static func other_static_func():
print("other static func")
static func third_static_func():
print("third static func")
class SomeClass:
uses SomeTrait
# Overridden static variable
var other_static_var = 1 # using 'static' keyword is optional
static var third_static_var = 1
# Overridden static function
func other_static_func(): # using 'static' keyword is optional
print("overridden other static func")
static func third_static_func():
print("overridden third static func")
func _ready():
print(SomeClass.some_static_var)
print(SomeClass.other_static_var)
print(SomeClass.third_static_var)
SomeClass.some_static_func()
SomeClass.other_static_func()
SomeClass.third_static_func()
print("ok")
If static function/variable is declared in a trait, when redeclared/overridden in class should using 'static' keyword is optional ? (currently it is)
This is not correct traits are not object and should not be instanced or called, I will look for way to better communicate this to prevent misuse. |
Personally, I strongly feel that the class MyClass:
uses MyTrait
static var some_static_var = 2 # inherited from MyTrait
# OR
some_static_var = 2 # also inherited from MyTrait The Simply having |
GDScript Trait System
Based on the discussion opened in:
The GDScript trait system allows traits to be declared in separate
.gdt
files or within atrait SomeTrait
block.Traits facilitate efficient code reuse by enabling classes to share and implement common behaviors, reducing duplication and promoting maintainable design.
Syntax Breakdown
Declaring Traits
Traits can be defined globally or within classes.
In a
.gdt
file, declare a global trait usingtrait_name GlobalTrait
at the top.trait
used for inner traits.Traits can contain all class members: enums, signals, variables, constants, functions and inner classes.
Example:
Using Traits in Classes
Use the
uses
keyword after theextends
block, followed by the path or global name of the trait.Traits can include other traits but do not need to implement their unimplemented functions. The implementation burden falls on the class using the trait.
Example:
Creating Trait files.
How Traits Are Handled
Cases
When a class uses a trait, its handled as follows:
1. Trait and Class Inheritance Compatibility:
The trait's inheritance must be a parent of the class's inheritance (compatible), but not the other way around, else an error occurs. Also note traits are pass down by inheritance, If a class is for instance "SomeTrait" also it here classes will be so.
Example:
2. Used Traits Cohesion:
When a class uses various traits, some traits' members might shadow other traits members ,hence, an error should occur when on the trait relative on the order it is declared.
3. Enums, Constants, Variables, Signals, Functions and Inner Classes:
These are copied over, or an error occurs if they are shadowed.
4. Extending Named Enums:
Named enums can be redeclared in class and have new enum values.
5. Overriding Variables:
This is allowed if the type is compatible and the value is changed.
Or only the type further specified. Export, Onready, Static state of trait variables are maintained. Setter and getter is maintained else overridden (setters parameters same and the ).
6. Overriding Signal:
This is allowed if parameter count are maintained and the parameter types is compatible by further specified from parent class type.
Example:
7. Overriding Functions:
Allowed if parameter count are maintained, return types and parameter types are compatible, but the function body can be changed. Static and rpc state of trait functions are maintained.
8. Unimplemented (Bodyless) Functions:
The class must provide an implementation. If a bodyless function remains unimplemented, an error occurs. Static and rpc state of trait functions are maintained.
9. Extending Inner Classes:
Inner classes defined in used trait can be redeclared in class and have new members provide not shadow members declared inner class declared in trait. Allow Member overrides for variables, Signals and function while extending Enum and its' Inner Classes.
Example:
Special Trait Features
10. Trait can use other Traits:
A trait is allows to use another trait except it does not alter members of the trait it is using by overriding or extending.
However, cyclic use of traits (TraitA uses TraitB and TraitB uses TraitA) is not permitted and will result in error.
11. Tool Trait:
if one trait containing the
@tool
keyword is used it converts classes (except inner classes) and traits using it into tool scripts.12. File-Level Documentation:
Member documentation is copied over from trait else overridden.
System Implementation Progress
as
)is
).gdt
files unattachable to objects/nodesBugsquad edit: