Wonderful! These types of experiments are probably the best way to learn all the deep little nooks and crannies of any programming language. I have a sandbox project dedicated to doing exactly this, so maybe consider that approach to protect your projects during other experiments.
First of all:
Absolutely agree with you there!
What’s interesting here is, what the error takes issue with is not the left side of your equation, but the right side - the integer 5. The error itself happens because of the + operator; while it does the same “adding” on the surface, it’s doing very different things under the hood, and + with strings is a totally different operator vs. + with ints. The error is basically trying to tell you that these data types are not directly compatible with the + operator. On the first and 3rd tests, this is why you have to write str(5)
to fix the error. This is called type casting in C#; I don’t know if there’s a different or equivalent term in GDScript, but you are essentially making the engine interpret this value as a string so that there is no longer any conflict.
I’m not sure why you would be seeing the test()
return type as a string, maybe because that’s the engine’s best guess based on what you have in the function, but the reason why the second line doesn’t throw an error is because of a feature unique to weakly-typed languages like GDSscript called “duck typing.” Long story short, if you don’t give it a data type in this situation, it will simply try to execute the code anyway and hope for the best - and in this case, it’s hoping test()
outputs a string. If you’ve been wondering why code completion isn’t great in GDScript, duck typing is the reason, but it does have its benefits.
Duck typing is a very unintuitive feature to understand, especially if you learned the basics of programming in strongly-typed languages like VB and C# (like I did). The docs have a decent introduction to duck typing, and I would definitely recommend checking out the last section of this page (don’t worry if it doesn’t make too much sense yet, as it’s definitely a bit advanced for where you are in the course. For the moment, just know that this exists):