Functions & Subroutines: Handy Little Helpers

by BASICwebmaster

The joy of using JB is being able to do the same thing multiple times, and still be able to tweak it. The bliss I speak of can be done through functions and subroutines. A Function is designed to return one value, based on the one given. For instance, this function:

 
print TrueOrFalse$(9, 12)
end
 
FUNCTION TrueOrFalse$(a, b)
if a < b then TrueOrFalse$ = "False" else TrueOrFalse$ = "True"
END FUNCTION
 

It gets two values, and returns "True" if the second number can be subtracted from the first without returning a negative value, "False", if it cannot. A subroutine works in a similar manner, but generally doesn't pass a value back to the program after it is done being executed. Here's an example:


input "What is your Name? "; username$
call GreetUser username$
'Main program here
end
 
SUB GreetUser user$
print "Hello, "; user$; ", Welcome to our program.
END SUB
  

A variation is the gosub [Branch]..return subroutine. It also has advantages and disadvantages. For instance, variables in a subroutine are not visible to the rest of the program, while those in a gosub [Branch]..return are not separate from the rest of the program. This can actually be an advantage, though.


print "WoodChucker 9000"
print
input "How much wood could a woodchuck chuck if a woodchuck could chuck wood? "; woodchucked
gosub [CheckWoodChucked]
print
print result$
end
 
[CheckWoodChucked]
if woodchucked = 13 then
 let result = "Correct! (Oh no, they no how I figured that out. Better hit the road...)"
else
 let result$ = "Wrong! Try again later."
end if
return
  

People always talk about objects and DLL's, but JB can use neither of those. For short, easy, reusable code, Functions and Subroutines are our versatile answer.