|
|
||
|
Hello,
I did some more experiments with metatables and metamethods, and came
across something I would consider curious. Consider this piece of
code:
function get_op_args(op1, op2)
if type(op1) == "number" then op1 = { val=op1 } end
if type(op2) == "number" then op2 = { val=op2 } end
return op1, op2
end
mt = {
__add = function(op1, op2)
op1, op2 = get_op_args(op1, op2)
return op1.val + op2.val
end,
__lt = function(op1, op2)
op1, op2 = get_op_args(op1, op2)
return op1.val < op2.val
end
}
t = { val = 17 }
setmetatable(t, mt)
now there is a table t that can be added and compared. Some tests show
that:
print(t + 4) --> 21
print(4 + t) --> 21
print(t < {val=4}) --> false
print({val=4} < t) --> true
work well and yield the expected result. However, neither of these
works:
print(t < 4)
print(4 < t)
The error I get is "lua: metamethods.lua:27: attempt to compare table
with number". From the documentation it would seem that this should
work, just as t+4 does. Or am I missing something?
rgds,
Gunnar