lua-users home
lua-l archive

Re: simply question about syntatic sugar

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


2015年06月06日 23:33 GMT+02:00 Rodrigo Azevedo <rodrigoams@gmail.com>:
> Let v be a usardata with a unary method, then
>
> v:abs() is a syntatic sugar for v.abs(v)
> v:reduce() is a syntatic sugar for v.reduce(v)
>
> etc
>
> This notation is very unpleasant. There is a problem if this behaviour of
> function calls
>
> v:abs is a syntativ sugar for v.abs(v)
> v:reduce is a syntatic sugar for v.reduce(v)
>
> was valid?
You can exploit the metatable mechanism so that v.Abs means v.abs(v).
Example:
mt = {__index = function(v,name)
 local method = type(name)=='string' and rawget(v,name:lower())
 if method then return method(v) end
end}
function cabs(v) return math.sqrt(v.x^2+v.y^2) end
tbl = setmetatable( {x=3, y=4, abs=cabs},mt)
tbl.Abs --> 5.0

AltStyle によって変換されたページ (->オリジナル) /