6

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!

4

3 回答 3

7

遗憾的是 C64 BASIC 不支持更复杂的功能

但是,它确实支持更复杂的子例程,这就是您在这种情况下想要的。

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

不幸的是,在 C64 BASIC 中将参数传入子程序并从子程序中返回值不是形式化的构造,因此您只需要使用如上所示的普通变量即可。

于 2016-07-16T22:30:23.697 回答
1

据我回忆,您可以使用 colan 虚拟地执行此操作,以便在一行中包含多个命令。不是最优雅的解决方案,但会让你打破局面:

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

变成

10 n=n+1: print n

请注意,您不能传递参数,因此您必须声明事物并让 BASIC 堆栈为您处理它。通常我会像这样构建程序:

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

有一阵子了; 从内存中,% 字符将变量声明为整数,类似于 $ 将其声明为字符串。

于 2016-07-18T12:42:25.123 回答
0

您可以使用现有的变量和数学命令DEF FN,例如,如果您想PRINT在 4 位 nybbles 中包含 0 到 10,可以这样做:

 0 DEF FN B(X)=SGN(X AND B)
 1 FOR I=0 TO 10: REM OUR COUNTER
 2 B=8: REM OUR BIT MARKER (128, 64, 32, 16, 8, 4, 2, 1)
 3 FOR J=0 TO 3: REM WE WANT 4-BIT NYBBLES, SO 0 TO 3 INCLUSIVE
 4 PRINT RIGHT$(STR$(FN B(I)),1);: REM CALLS OUR FUNCTION
 5 B=B/2: REM MOVES TO NEXT BIT MARKER
 6 NEXT J: REM PROCESS FOR LOOP J
 7 PRINT: NEXT I: REM NEW LINE THEN PROCESS FOR LOOP I

我尝试过嵌套函数,但它变得太混乱了。事实上,我还没有看到很多使用DEF FN. 也许一些高级工匠时髦 BASIC 程序员使用它们?

于 2017-05-08T15:48:04.083 回答