元表事件 |
|
Lua 5.3 引入了使用真整数的能力,以及位运算。这些运算类似于加法运算,但如果任何操作数既不是整数也不是可以强制转换为整数的值,Lua 将尝试元方法。
t1a = {} t1b = {} t2 = {} mt1 = { __eq = function( o1, o2 ) return 'whee' end } mt2 = { __eq = function( o1, o2 ) return 'whee' end } setmetatable( t1a, mt1 ) setmetatable( t1b, mt1 ) setmetatable( t2, mt2 ) print( t1a == t1b ) --> true print( t1a == t2 ) --> false
t1
和 t2
引用的是同一个表,则不会为 t1 == t2
调用 __eq
方法。
function foo (o1, o2) print( '__eq call' ) return false end t1 = {} setmetatable( t1, {__eq = foo} ) t2 = t1 print( t1 == t2 ) --> true -- string '__eq call' not printed (and comparison result is true, not like the return value of foo(...)), so no foo(...) call here t3 = {} setmetatable( t3, {__eq = foo} ) if t1 == t3 then end --> __eq call -- foo(...) was called
a > b == b < a
a >= b == b <= a