Attempt to compare string and number

I’m getting attempt to compare string and number error in if myTextButton.Text <= myTable.Number.

I just want to understand why sometimes I can compare string to numbers without conversion and sometimes not… (I know I can use tostring() or tonunber())

For example:

> n=1
> t="1"
> print(n==t)


print( 5 * "5" ) --> 25

no errors…

if myTextButton.Text <= myTable.Number

is giving that error…

What’s the logic for that?

It has to do with the way strings are represented, string are generally represented using ASCII. Thus they are compared by using the ASCII code for each character inside of the string, so this is why strings can only be compared with other strings, when using the >, <, <=, >=.

1 Like

I made a new test:

> n=1
> t="1"
> print(n==t) --> false
> print(n<=t) --> print(n<=t):1: attempt to compare number and string

So if I compare with == it’s ok, but <= I get the error…

Well this is because you’re checking if the string value is the same as the number value and it returns false cause they aren’t the same datatype. You can’t check if a string is bigger than a number.

1 Like

Yes you can use the == operator, I mentioned the ones you cant use. When using the other operators it will not work because to check the difference it uses ASCII codes, which is a unique number for each character, adds them up, then compare the total for each string. For example if you print:

print( "abcdefg" < "z") --this will be true since the numerical code for z is much higher