|
A subroutine (also called a "module") is a "mini-program" inside your program. In other words, it is a collection of commands--and can be executed anywhere in your program. To create a subroutine:
To use the subroutine:
The following example does not use subroutines:
INPUT text$ PRINT "The text you entered was: "; text$ PRINT "Enter some text:"; INPUT text$ PRINT "The text you entered was: "; text$ PRINT "Enter some text:"; INPUT text$ PRINT "The text you entered was: "; text$ PRINT "Enter some text:"; INPUT text$ PRINT "The text you entered was: "; text$ PRINT "Enter some text:"; INPUT text$ PRINT "The text you entered was: "; text$ PRINT "Enter some text:"; INPUT text$ PRINT "The text you entered was: "; text$ PRINT "Enter some text:"; INPUT text$ PRINT "The text you entered was: "; text$ By using a subroutine, the above program can be simplified like this:
CALL GetText CALL GetText CALL GetText CALL GetText CALL GetText CALL GetText SUB GetText
INPUT text$ PRINT "The text you entered was: "; text$ END SUB The following is even more concise:
SUB GetText
INPUT text$ PRINT "The text you entered was: "; text$ Parameters Parameters are numbers and strings that you pass to a subroutine, much like a QBasic command.
CALL OutputNumber(16) ' Notice the parentheses around the parameter "num." ' Any variables placed inside the parentheses are set as ' the subroutine's parameters. SUB OutputNumber (num)
END SUB
Functions A function is the same as a subroutine, except it returns a value. Also, you must leave out the CALL command. To return a value, set a variable with the same name as the function.
FUNCTION Add (num1, num2)
END FUNCTION
Since a function can return a value, the name of the function can end with special characters (see Variable types, Using special characters).
' the function returns a string. PRINT Add$("Hello", "World") FUNCTION Add$ (str1$, str2$)
END FUNCTION
Feel free to distribute this tutorial, upload it to your website, link to it from your site, etc. http://www.geocities.com/progsharehouse/qbtutor Mirror: http://development.freeservers.com/qbtutor |