Went back to good old qbasic for nostalgic reasons and have never used types and functions in qbasic before as I was very young that time.
TYPE Vector2
x AS SINGLE
y AS SINGLE
END TYPE
FUNCTION Vector2Mag (a AS Vector2)
Vector2Mag = SQR((a.x * a.x) + (a.y * a.y))
END FUNCTION
FUNCTION Vector2Add (a AS Vector2, b AS Vector2)
DIM r AS Vector2
r.x = a.x + b.x
r.y = a.y + b.y
Vector2Add = r
END FUNCTION
But i get
Illegal SUB/FUNCTION parameter on current line
using qb64 in both first function lines. Google didn't help as it looks like I am doing everything right. I checked passing multiple variables, specifying a type for a parameter, how to use types but nothing really helped.
Thanks guys.
It has been a while, but I believe the problem is actually that you can't return a UDT (user defined type, a.k.a. "any type that is not built in"). What you need to do is pass a third argument to Vector2Add
and make it a SUB
. For example:
SUB Vector2Add (r AS Vector2, a AS Vector2, b AS Vector2)
r.x = a.x + b.x
r.y = a.y + b.y
END SUB
The SUB
is almost an exact translation with equivalent C code, aside from syntax differences. My reasoning is that you usually add a type suffix to the name of a FUNCTION
in QB or it will use its default type, which may have been overridden by DEFxxx M-N
(or _DEFINE
in QB64; and no you can't use _DEFINE
with UDTs). For example, returning a string:
'Default type for all identifiers beginning with 'S' is STRING.
' Type suffixes, "AS xxxx" clauses and future "DEFxxx" items override the behavior.
DEFSTR S-S
FUNCTION swapFirstLast$ (s)
swapFirstLast$ = RIGHT$(s, 1) + MID$(s, 2, LEN(s) - 2) + LEFT$(s, 1)
END FUNCTION
QB64 is kinda limited in this regard since it aims to be as compatible with the syntax used by QuickBASIC 4.5 as possible. FreeBASIC, another language based on QB, has no such restriction:
'Notice the "AS Vector2" at the end of this next line and the RETURN statement
' that FB introduced for FUNCTIONs (originally it was used to return from an
' "old-style" subroutine that was invoked via the GOSUB statement).
FUNCTION Vector2Add (a AS Vector2, b AS Vector2) AS Vector2
DIM r AS Vector2
r.x = a.x + b.x
r.y = a.y + b.y
RETURN r
END FUNCTION
The important point to remember is that QB64 is basically still QB, except it will compile code to run on modern operating systems (rather than DOS). FreeBASIC, on the other hand, chose to sacrifice some compatibility in favor of creating a more "modern" language that retains QB's syntax.