Learning how to use DEF will help you write better programs, and also be able to use libraries and other cool features of SmileBASIC. It will also help you if you plan on working with other programming languages.
DEF vs. GOSUB
If you have used GOSUB before, DEF isn't really that different. The only major difference is:
- GOSUB is not used in programming languages anymore
- DEF is used in almost all programming languages
Like GOSUB, DEF lets you make a bunch of code and repeat it when you need it. Unlike GOSUB, DEF has full support for parameters, which are variables that are set at the beginning of a DEF. DEF makes better looking code compared to GOSUB, and DEF also makes code more readable.
SPEAK "Hello, world!"
DEF SPEAK S$
FOR I=0 TO LEN(S$)-1
VSYNC 5
?S$[I];
BEEP
NEXT
VSYNC 60
END
'vs GOSUB:
S$="Hello, world!"
GOSUB @SPEAK
@SPEAK
FOR I=0 TO LEN(S$)-1
VSYNC 5
?S$[I];
BEEP
NEXT
VSYNC 60
RETURN
Also, if the next line of code is a DEF, it automatically starts ignoring what code is inside the DEF, unlike GOSUB, which would run through the code until it hits a RETURN and gives an error.
How to use DEF
There are 3 different DEF types:
- DEF name(v1,v2,...)
- Takes: up to 255 values, or even 0 values.
- Gives back: 1 value.
- DEF name v1,v2,...
- Takes: up to 255 values, or even 0 values.
- Gives back: nothing.
- DEF name v1,v2,... OUT o1,o2
- Takes: up to 255 values, or even 0 values.
- Gives back: up to 255 values.
Each DEF is ended with an END statement. For example:
DEF HELLOWORLD S$
PRINT S$
BEEP
WAIT 30
PRINT "Hello World!"
END
will be finished soon...