Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multi-line functions in Commodore 64 BASIC

So, I'd like to write larger functions in Commodore 64 BASIC. So far, from what I'm seeing from other sources (such as various C64 wikis, as well as the user's manual for the C64 itself,) function definitions can only be one line long. That is to say, I can't seem to find an analogous construct in BASIC to brackets/whatever else other languages use to delineate code blocks.

Does anyone know how I'd write code blocks in BASIC that are more than one line?

Example of one-line function:

10 def fn X(n) = n + 1
20 print fn X(5) rem Correctly called function. This will output 6

But I can't do something like:

10 def fn X(n) = 
20 n = n + 1
30 print n
40 rem I'd like the definition of function X to end at line 30 above 
50 fn X(5) rem Produces syntax error on line 40

Thank you for your time!

like image 484
user3255569 Avatar asked Jul 16 '16 21:07

user3255569


2 Answers

Sadly C64 BASIC doesn't support more complicated functions.

It does however support more complicated subroutines, and that's what you want in this case.

10 rem you can set up n in advance here
20 n = 23
30 gosub 50
40 rem n is now 24
50 rem start of subroutine; this line is not needed, it's just here for clarity
60 n=n+1
70 print n
80 return
90 rem now you can call the subroutine on line 50 and it'll return at line 80

Unfortunately passing parameters in to and returning values out of subroutines in C64 BASIC aren't formalized constructs, so you'll just have to work with ordinary variables as shown above.

like image 181
Feneric Avatar answered Sep 22 '22 12:09

Feneric


From what I recall, you can do this virtually using a colan to have multiple commands on one line. Not the most elegant solution, but will let you break things up:

10 def fn X(n) = 
20 n = n + 1
30 print n
40 rem I'd like the definition of function X to end at line 30 above 
50 fn X(5) rem Produces syntax error on line 40

Becomes

10 n=n+1: print n

Note that you cannot pass arguments, so you would have to declare things and let the BASIC stack take care of it for you. Commonly I would structure programs like so:

1     rem lines 1-99 are definitions.
2     n% = 0 :  rem this declares the variable n as an integer, initializing it to 0
100   rem lines 100-59999 are the core code
101   n%=5 : gosub 60100
59999 end : rem explicit end of the program to ensure we don't run into our subroutine block
60000 rem lines 60000+ are my subroutines..
60100 n% = n% + 1 : print n% : return

It's been a while; from memory the % character is what declares a variable as an integer, similar to $ declaring it as a string.

like image 45
tendim Avatar answered Sep 22 '22 12:09

tendim