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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With