lua-users home
lua-l archive

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


On 21 August 2015 at 19:33, Sean Conner <sean@conman.org> wrote:
>   I do have a Lua module [1] where each userdata created gets its own unique
> metatable.  I did that so I could associate additonal values at run time to
> the userdata, like:
>
>         X = require "Xcore"
>
>         display = X.open_display()
>         window  = display:window( ... I won't bore you with details here )
>
>         -- now add some additional values
>
>         window.comment = "This is the main window"
>         window.child   = X.sub_window(...)
>
>   When a window (as a userdata) goes out of scope, the __gc method will
> close the window and because each userdata gets its own metatable, the
> metatable itself will be subject to garbage collection and thus any
> resources (like windows, or fonts or anything else where the sole reference
> is in that metatable) will be reclaimed as well.
>
>   This new method breaks that.  I'm not sure what I'm doing is *good* [1]
> but it's a method that currently works.
>
>   -spc
>
> [1]     It wraps Xlib.  Not suitable for general consumption, even assuming
>         anyone knows how to program to Xlib anymore.  It uses some
>         questionable techniques [2] that I'm not sure should get out of the
>         laboratory.
>
> [2]     No, really!  I'm be surprised if you could get the code to work on
>         your machine.
>


Instead of giving each instance it's own metatable; use the
'uservalue' to associate a table with it.
(see other thread from today: "lua_setuservalue() - what is it for?")

I find it's good to consider the metatable of an object as it's
"class" if you're into OO.
then e.g. `a instanceof someclass` is `getmetatable(a) == someclass`.
Of course this is only one way of many to do things :)