lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]





On 22 September 2013 13:10, Jayanth Acharya <jayachar88@gmail.com> wrote:

On Sun, Sep 22, 2013 at 5:29 PM, liam mail <liam.list@googlemail.com> wrote:

On 22 September 2013 12:47, Jayanth Acharya <jayachar88@gmail.com> wrote:
In the list of published metamethods available in every document that I read, I seem to be unable to find __gt and __ge anywhere. Are those really no present, or am I missing something (like checking the right place, doc) ?

If those are really absent, then does it mean we cannot use metatables to support the > and >= operators for say table comparison ?


See [1] and the notes after each of the "le" and "lt" operators, the operators you mention come for free when you define other operators.



Thanks Liam. Probably 5 minutes after posting that question, I found a mail written by Peter Hill way back 2004, asking this question, and also the answer, but I had completely missed the note in the manual.

So, if I understand this correctly, I cannot use the < and <= operators in Lua code while comparing 2 tables say 'a' and 'b', where the intent was to check (a < b). However I could rewrite the Lua code as (b > a). Right ?


> "the operators you mention come for free when you define other operators."

This does not mean you can not use the operators you have defined that would be bizarre.
Maybe a simple piece of code will help in understand what is happening.

$ cat ./ops.lua 
local a, b = 1, 2
local c, d = a > b, a < b

$ luac-5.2.2 -l -l ./ops.lua

main <./ops.lua:0,0> (11 instructions at 0x8ad4b50)
0+ params, 4 slots, 1 upvalue, 4 locals, 2 constants, 0 functions
1 [1] LOADK     0 -1 ; 1
2 [1] LOADK     1 -2 ; 2
3 [2] LT       1 1 0
4 [2] JMP       0 1 ; to 6
5 [2] LOADBOOL 2 0 1
6 [2] LOADBOOL 2 1 0
7 [2] LT       1 0 1
8 [2] JMP       0 1 ; to 10
9 [2] LOADBOOL 3 0 1
10 [2] LOADBOOL 3 1 0
11 [2] RETURN   0 1
constants (2) for 0x8ad4b50:
1 1
2 2
locals (4) for 0x8ad4b50:
0 a 3 12
1 b 3 12
2 c 11 12
3 d 11 12
upvalues (1) for 0x8ad4b50:
0 _ENV 1 0


You can see that the third instruction[1] is LT and the seventh is also, Lua just swapped the stack slot indices to provide both operators.

[1] If you take the first instruction to be number 1