So since I was bored I decided I'll mess around with operators by providing invalid operands for Lua to throw an exception.
I decided to do this:
print("a" < "b")
And I got true
in the output which surprised me. This used to not work. You were never able to use <=
, >=
, <
, or >
with string operand. You would get an exception message.
I thought maybe the result was based on string length since at first I had this:
print("accordion" > "guitar")
But it evaluated to false
, and #"accordion" == 9
and #"guitar" == 6
. So what is the result based on?
It is based off their character codes. For example you have ASCII or Unicode which have character tables where every character has a value. In the case of "a" < "b"
, 'a' comes before 'b' in the table so therefore it is true. The operators compare their actual codes.
If you want to see the codes you can do...
print(string.byte("a")) -- 97 print(string.byte("b")) -- 98
or
print(string.char(97)) -- a print(string.char(98)) -- b
When comparing large strings, it will check the first characters, if they are equal, then the second, and so on until one of them doesn't match. This is because strings are simply an array of characters.
It is also worth noting that "A" ~= "a"
because capital and lower case letters are different codes.