lua-users home
lua-l archive

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


On 9 Jun 2013, at 18:42, Philipp Janda wrote:

> But then you need to maintain a set of valid userdata handles for each class to make it safe, or else:
> 
>    do
>      local o1, o2 = class1.new(), class2.new()
>      o1.udata, o2.udata = o2.udata, o1.udata
>    end
>    collectgarbage()
>    collectgarbage()
>    -- boom

I don't understand the point of your example. udata is a private member of the object, not meant to be altered in Lua code (I tend to prefix with _). If you go and mess with it, then that's your fault, and so is the resultant crash.

With full userdata, I believe you have the same problem if someone does

do
	local o1, o2 = class1.new(), class2.new()
	local o1_mt, o2_mt = getmetatable(o1), getmetatable(o2)
	o1_mt.__gc, o2_mt = o2_mt.__gc, o1_mt.__gc
end

Now, I think you can use the __metatable metamethod to stop this, but then you lose the ability to modify the metatable from Lua which loses a lot of flexibility.

> ... and __gc for tables only works in Lua 5.2 and up.

Fair enough, I didn't know that, but I only use Lua 5.2

Kevin