lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


于 2011年10月20日 08:12, Daurnimator 写道:
A small feature request to distract you all from the noise on the list recently:

I often find myself writing code like
mt.__newindex = function ( t , k , v )
     v = dosomethingwithv ( v )
     rawset(t,k,v)
end

Could we make it so the return value of __newindex is then set as the
value in t?

It will be backwards compatible, as the majority of code out there
don't return anything from __newindex operations.

Benefits
  - One less line of code
  - __newindex operations can now do a tail call; `function (t,k,v)
return dosomethingwithv(v) end;
  -  I assume it can be optimised quite well in the actual
implementation, as the key has already been hashed; and we know its
not already in the table.


Daurn.

the __newindex meta method, or event, is triggered when a non-existing field of one table is being set.
so the semantic type is an assignment *statement*, not an *expression*. so it is meaningless to return values.

so the __index event is to evaluate an expression, while __newindex is to execute a statement.