lua-users home
lua-l archive

Re: comparative functions and "same metamethod" gotcha

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


On Wed, Jun 4, 2014 at 11:45 PM, Andrew Starks <andrew.starks@trms.com> wrote:
> return setmetatable({}, {
> --for brevity, I'm only including the function in question.
> __eq = function(a, b) return a.url == b.url end ,
>
> })
this is a common idiom that i don't understand why is so common. to
create an object, you create an empty table and set a metatable.
that's ok. in this case, the methods don't have upvalues, so they
should be the same closures, or at least, they could be. but why do
you create a new metatable for each object instance?
wouldn't it be much better to do something like this?
local _mt = {
 __eq = function(a,b) return a.url == b.url end,
}
function constructor(url)
 .......
 return setmetatable({}, _mt)
end
here the metatable is defined once and used for every object. you
could also use it as a 'class test', by comparing it:
getmetatable(obj)==knownmetatable
at least, i guess it could eliminate Andrew's problem
-- 
Javier

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