Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

What is the result of relational operators (but not == and !=) based on when operands are strings?

Asked by 5 years ago

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?

1 answer

Log in to vote
2
Answered by 5 years ago
Edited 5 years ago

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.

0
thx bro programmerHere 371 — 5y
Ad

Answer this question