[Gambas-user] Gambas scripting, Type mismatch error.
d4t4full at gmail.com
Thu Nov 19 11:59:54 CET 2020
*On 17/11/20 15:03, Bruce Steers wrote:*
> Is this a bug in the scripter or bad coding technique on my part?...
> getting a type mismatch error if i do not wrap variables in parentheses?
> doesn't happen like this in normal gambas exe.
> If I use code like the following in a gbs script...
> Dim iVal As Integer = 1
> Print iVal ' This prints '1'
> Print iVal + 1 ' this prints '2'
> Print "Val = " & iVal ' this prints 'Val = 1'
> Print "Val = " & iVal + 1
> ' This gives the following error..
> ' MMain.?.0: #6: Type mismatch: wanted Float, got String instead
> Print "Val = " & (iVal + 1) ' this works and prints 'i = 2'
I guess the problem is ambiguity between the numeric addition / string
concatenation "+" operator and the numeric parameters supplied.
The "&" expects and returns strings, the "+" expects and returns either
numbers or strings.
So you seem to have a string/number salad in
Print "Val = " & iVal + 1
I guess the interpreter sees the "&" and "+" as having the same
priority, so it works left to right:
There's a string ("Val = "), then concatenate a number-coerced-to
-string (iVal), and then, to that result (a string), ADD a number...
That's not possible: TYPE MISMATCH.
When the parenthesis are inserted, they give the "+" numeric operator
priority over the "&" string operator and the numeric result is coerced
to string: It works.
I like clarity (sometimes too much, I confess); I would have used
Print "Val = " & CStr(iVal + 1)
And that should not fail.
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the User