2

I created a metatable where __add and __sub take a table and an number. How does Lua determine which to use? Consider the two situations below with table T (with metatable described)

local n=-10
local V=T+n

and

local n=-10
local V=T-n

Which gets called?

I have experimented with various combinations but fail to see a pattern.

4

2 回答 2

5

Created a metatable where __add and __sub take a table and an number.

__add and __sub take two operands. One of them will necessarily be a table or userdata which has your metatable, the other can be anything at all. Lua doesn't care about the type of the other operand.

If either operand has a metatable with a handler for the particular operator (+ -> __add, - => __sub), that handler will be called.

In your example, Lua not only doesn't care if n is positive or negative, it doesn't care if it's a number. The - in -n has nothing to do with the __sub metamethod -- that's the unary minus operator, whereas __sub handles the binary minus operator.

How does Lua determine which to use?

The + operator is an "__add" event. When you sayd op1 + op2, Lua checks op1 for a metatable with an __add handler. If it finds one, it calls it. Otherwise it checks op2.

于 2012-12-14T07:42:46.977 回答
3

It is the sign of the two operands operator in the source code which is determinant.

It does not care whether the operand value are negative or positive numbers. It does not even care whether your n is actually a number or a value of another type.

local n=-10  
local V=T+n  -- __add called

local n=-10
local V=T-n  -- __sub called
于 2012-12-14T06:29:21.063 回答