lua-users home
lua-l archive

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



On Thu, Jun 5, 2014 at 8:56 PM, Javier Guerra Giraldez <javier@guerrag.com> wrote:
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

Normally I do exactly that. In this case, I wanted the object to be immutable, except for a couple of fields. So I made the metatable unique for every object and referred to an `obj` upvalue in most of the metamethods. The __eq function doesn't use upvalues, which means the first argument position has to do an __index lookup for the `url` field.

Obviously Lua, at first at least, picked up on the 'same-ness' of the __eq function and only made one version, shared between all objects. Then the garbage collector hit and then it made them fragment.

Having it make them consistently separate is perfectly fine. Having it make them the same at first and _then_ to  separate  them is crazy confusing and, IMHO, not okay for a scripting language to do to a fella.

However, it dawned on me that this could be a 5.3 bug. Is that a possibility, or is it normal for 2 functions to be the same reference, and then for a garbage collection cycle to change that?

--Andrew