Jumps and subroutines
Older code moves around with labels: goto to a label, on n goto to the
nth of a list, and gosub to a subroutine that returns. tiko keeps the
first two and refuses the third.
gosub belongs to the older dialects:
'' GOSUB jumps to a label; RETURN comes back. tiko refuses it.
dim as long total = 0
gosub add_one
gosub add_one
print total
end
add_one:
total = total + 1
return
gosub.bas(3,7): error TKO0409: 'GOSUB' is not available in the fb dialect
|
3 | gosub add_one
| ^
gosub.bas(4,7): error TKO0409: 'GOSUB' is not available in the fb dialect
|
4 | gosub add_one
| ^
A gosub subroutine has no parameters and no local variables: everything it
touches is shared with its caller. Rewritten as a sub, the variable it
changes becomes a byref parameter:
'' The subroutine as a sub: what it changes is passed byref.
sub AddOne( byref total as int32 )
total += 1
end sub
dim as int32 total = 0
AddOne( total )
AddOne( total )
print total
Output
2
on … goto still compiles:
'' ON n GOTO jumps to the n-th label in its list. tiko accepts it.
for choice as long = 0 to 4
print "choice"; choice; ": ";
on choice goto add, list, quit
'' Out of range -- 0, or past the end of the list -- falls through.
print "no such option"
goto next_choice
add:
print "adding a record"
goto next_choice
list:
print "listing the records"
goto next_choice
quit:
print "quitting"
next_choice:
next
Output
choice 0: no such option
choice 1: adding a record
choice 2: listing the records
choice 3: quitting
choice 4: no such option
A value of 0, or one past the end of the list, jumps nowhere, and execution
carries on with the next line. In modern code, select case says the same
thing with no labels and no goto at the end of every branch:
'' The same menu with select case: no labels, no jumps.
for choice as int32 = 0 to 4
print "choice"; choice; ": ";
select case choice
case 1
print "adding a record"
case 2
print "listing the records"
case 3
print "quitting"
case else
print "no such option"
end select
next
Output
choice 0: no such option
choice 1: adding a record
choice 2: listing the records
choice 3: quitting
choice 4: no such option
Other older statements are refused the same way, each with TKO0409 naming
the keyword: resume, let in front of an assignment, call in front of a
call, the def statements such as defint, and option statements. Numbered
lines are refused too; a label is a name followed by a colon on a line of its
own.
Activities
- Add a fourth option to both menus and compare how much each one changed.
- Make
AddOnetake the amount to add as a second parameter.