Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Lua has the `<=` opcode and metamethod?

In addition to == and <, Lua has the <= opcode and metamethod (OP_LE, TM_LE).

Documentation says that

in the absence of a "le" metamethod, Lua tries the "lt", assuming that a <= b is equivalent to not (b < a)

but why there is '<=' in the first place? Why can't it always use not (b < a) for a <= b?

Update:

If it's all about DSLs, "language hooks", etc, then why Lua doesn't have ~=, >, and >= opcodes and metamethods?

like image 684
Abyx Avatar asked Dec 27 '22 04:12

Abyx


1 Answers

Let's implement sets. It would be really neat to use the order operators for inclusion tests. a < b would mean "a is a proper subset of b". a = b would mena "a and b are equal". a <= b would mean "a is a subset of b" (not necessarily a proper one, so they might be equal).

Now consider

a = Set:new{1, 2, 3}
b = Set:new{"a", "b", "c"}

Now neither a <= b nor a < b is true. Why is that? Because the subset relation only defines a partial order. The logical assumption that a <= b is equivalent to not(a > b) is only valid for totally relationships that define a total order.

(Example inspired by "Programming in Lua, 3rd Edition" p. 131)

EDIT:

To address your update. Why doesn't have Lua metamethods for ~=, > and >= with regards to DSL implementation?

Even on partially ordered sets, the following are always true:

a > b    <==>   b < a
a >= b   <==>   b <= a
a ~= b   <==>   not (b == a)

Defining different meanings for < and > (except for switched order) would make your code really confusing, don't you think? Same thing if two a and b could be both equal and unequal (or neither). I guess, that's why Lua makes the assumption, that it can always implement these three operators in terms of the others.

like image 50
Martin Ender Avatar answered Dec 28 '22 17:12

Martin Ender