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

Could use tutorial on DEFs.

Root / Programming Questions / [.]

KrondeloCreated:
So, I could really use some sample code on DEF, I need to know if there are necessary parameters. Mainly I ask because I would like to know how they are more robust/useful than using GOTO's, and when to use them and when not to. Also, it seems confusing I thought you just named the DEF, and then types in that name when you want to execute. Lastly, how do these differentiate from Functions?

The parameters used when you use DEF are optional. However, if you declare a def with parenthesis(See B), then you must use the returned value for something(Assign a variable, print it or use it as a parameter). Here is a code with different cases.
DEF helloWorld
 ? "Hello world"
END

'=========================================================
'Type 1
'Def A [params....]
'END

Def A S1$,S2$
 ?S1$+" "+S2$
END

'=========================================================
'Type 2
'Def B([params...])
' return 0
'END

DEF B(S1$,S2$)
 return S1$+" "+S2$
END

'=========================================================
'Type 3
'Def C [params...] out [output...]
'END

DEF C S1$,S2$ out S3$
 VAR S$ 'Let call this variable local S$
 S$=S1$+" "+S2$
 S3$=S$
END

'=====================================================================


VAR S$ ' Let call this variable global S$
VAR R$

helloWorld
A "hello","world"
S$=B("foo","bar")
? S$
C "abc","def" out R$
? R$
? S$
Notice that variable S$ appear both inside C and outside. The variable inside C is modified after printing the global S$ but when you print that variable at the end of the code, it remain without modification. This happens because there exist a feature called scope. All variable declared outside a function are part of the global scope, but when you create a variable inside a function they stay alive until the function end. Also, you could access a variable that exist on the global scope in a function, but only if there isn't another variable with the same name in the function's scope. You should use DEF when you need to use the same block to return something or if you want to keep few variables on the global scope(This is useful when you have a big project ). Also, compared to GOTO, a function has slightly a slower performance so keep this in mind. If you are confused with the function declaration, you can write them in camelCase. This could help you to tell if something is a variable or a function.

Ok, think I got most of it. So basically a variable declared inside a DEF is local to that DEF until it ends.