Chapter 7: Creating SUBs and FUNCTIONs (Part II)
|
7.1 |
Introduction
As we've discussed in the previous chapter, creating SUBs isn't difficult. Creating FUNCTIONs in QBasic is similar to creating SUBs, the main difference is that a FUNCTION has a return value attached to it. |
7.2 |
QBasic's built-in FUNCTIONs
QBasic offers many built-in functions, let's take the graphics function POINT for example. POINT is used in graphics mode to get the colour of the pixel at (X,Y). Just pretend we're doing a simple collision detection routine, and want to know the colour of the pixel at (100,50)
Colour = POINT(100,50) See, POINT is a function because it returns a value. All functions must be on the RHS (right-hand side) of an assignment. Just like a SUB, a FUNCTION can accept any number of parameters you define.
|
7.3 |
Get to the POINT :)
Fine, let's get to the point, how do you create a FUNCTION?
FUNCTION ReturnMax%(Num1%, Num2%)
IF Num1% >= Num2% THEN
ReturnMax% = Num1%
ELSE
ReturnMax% = Num2%
END IF
END FUNCTION Quite obviously, this function returns the max of two numbers. So how does it work? Since a function returns a value, we need to specify what data type (see Chapter 2). As you can see, ReturnMax% is an integer type, so it will return an ... integer value! Some people ignore the % sign, but let's avoid this bad programming style.
ReturnMax% = Num1% is assigning the return value to Num1%, but note that this DOES NOT terminate a FUNCTION, you can assign infinitely many return values. Some people don't understand this:
FUNCTION ReturnMax%(Num1%, Num2%)
ReturnMax% = 1234 ' Keep going...
IF Num1% >= Num2% THEN
ReturnMax% = Num1%
ELSE
ReturnMax% = Num2%
END IF
END FUNCTION When the function is first called, the return value is 1234, but we're not done yet... eventually the return value is one of Num1% or Num2% depending on which one is larger.
|
7.4 |
Final notes
There's a lot to cover when dealing with SUBs/FUNCTIONs, most of the information is documented in QBasic's help file. I haven't covered shared variables and changing values of the parameters. I'll cover variable sharing later, but changing the value of a parameter is quite simple, so try this yourself. |
|
|