LoginLogin
Nintendo shutting down 3DS + Wii U online services, see our post

Can DEF make overload functions?

Root / Programming Questions / [.]

NeatNitCreated:
I'm still waiting for the release of SmileBASIC in the UK, and meanwhile fantasizing about the platformer that I'm going to make. I figured I might be able to separate the engine from the game, and then release the engine for anyone else's use and/or expansion. While thinking about some of the functions the engine could have, I realized that being able to define a function with a few overloads would be best. If you don't know what overload means, it's having the same function name take a different set of inputs. For example, COPY has two overloads: one of them works between two arrays, and the other works between an array and a @label. So I just wanted to ask you guys who already have the game, does it allow me to make overloads for my custom-defined functions? For example, have a function called ADD that accepts two strings, and a different function also called ADD that accepts two numbers? Thanks

Unfortunately, no, parameters are not even type-checked. Though if you wanted, you could make a function called ADD$ to signify it is to be used on strings. There are ways we've discovered recently to tell the difference between a number and a string, so to an extent you could use IF statements to implement your own overloading. Though there's still no way to have a function accept differing numbers of arguments.

wait, in SmileBASIC you can have a variable that doesn't end with $ be a string, and a variable that ends with $ be a number? That's so weird. How can you tell the difference then?

That only applies to function parameters. Normal variables will error if you try to assign the wrong type to them. And yes, it's really weird. I'll probably eventually write a Resource about type checking, but I'll clue you in on the main trick. You can use the fact that all strings are considered "true" in an IF statement. Also, multiplying a string by 0 will return the empty string. So to check if X is a string, you can do:
IF X*0 && X*0==X*0 THEN PRINT "X is a string!"
The reason for the X*0==X*0 comparison is that if X is Infinity or NaN, multiplying by 0 will return NaN which counts as "true". However, NaN is considered not equal to NaN, so that comparison makes sure only strings get through.

It applies not only to function parameters, but to OUT variables inside their DEF blocks.
DEF TEST OUT X
X="String!"
END
The above code will work whether you use X, X$, X%, or X#.

I consider those to be parameters as well (output parameters as opposed to input parameters), but that's a good clarification regardless.