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

Strange errors with DEF block

Root / Programming Questions / [.]

SP_SourCreated:
In a project I have, I defined a function that returns whether or not a button is held down (so I don't have to have "IF (BUTTON() AND #[whatever button])==#[button] THEN dowhatever" every time I get button input). It originally went like this:
DEF BTN(B)
IF (BUTTON() AND B)==B THEN RETURN 1
END
(Later)
PRINT BTN(#B)
When I tried to run that, I would get a "type mismatch error" on the PRINT line. I wondered why and tried passing the function a string, which led to a type mismatch error not on that line but in the middle of the function. I added VAL() to it, which still led to a type mismatch error. It seemed that the function wouldn't accept integers at call, but in the function itself accepted integers only. This confused the heck out of me until I fixed it with the below:
RETURN 0
(After the IF statement) I can see how that line not being there would cause error, but I don't at all see how it would cause type mismatch errors of all things. Any ideas?

I think since it wouldn't return ANYTHING unless the button was held, the type was undefined or something. Either way, you need it to be possible to return a variable in every condition, or else this happens I'm fairly sure.

Yeah, basically any function defined with the parameter(s) enclosed in brackets must return a single value. Your example can END without RETURNing. DEF FUNCTION(PARAM) must RETURN a single value DEF FUNCTION PARAM must not return anything DEF FUNCTION PARAM OUT A,B,C must(?) define the variables A, B, and C before ENDing. I still forget and define/call my functions incorrectly :-)

Yes, a common error in many programming languages. A DEF block must have all paths have a return value. So if the IF statement turned out to be FALSE, it kinda just ends. Then, when PRINT tries to see what BTN outputted, it sees the SB equivalent to NULL and crashes the program. So a fix would be:
DEF BTN(B)
IF (BUTTON() AND B)==B THEN RETURN 1 ELSE RETURN 0
END
(Later)
PRINT BTN(#B)
that way, all paths have a return value. You could also just put the RETURN 0 after the IF statement instead of adding an ELSE block:
DEF BTN(B)
IF (BUTTON() AND B)==B THEN RETURN 1
RETURN 0
END
(Later)
PRINT BTN(#B)