lua-users home
lua-l archive

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


There was a discussion on this list on this subject with some nice comments from Robert which inspired the current pattern for callbacks in lubyk: http://lua-users.org/lists/lua-l/2011-01/msg00218.html

The garbage collection is:

Lua ---> userdata ---> fenv ---> thread --> function

Since the function is not stored in a global table (as you do with luaL_ref), gc management is easy.
 
To reduce the housekeeping even further work when a C++ object has many callbacks (and to allow metamethods for callbacks and properties, etc), I am now considering storing a "self" table (in the useradata env or Lua thread stack) and doing the callback work as:

self[callback_name](self, …)

The garbage collection scheme will be: 

Lua ---> userdata --> fenv/_ENV ---> self --> [callback1, callback2, …]

Gaspard

On Sat, Jul 30, 2011 at 11:03 AM, Gregory Bonik <gregory@bonik.org> wrote:
Valeriy E. Ushakov wrote:
> Can you break the dependency by making on_click pass the object to the
> handler?
>
>   b:on_click(function(b) b:some_method() end)
>

Yes, but it is only a partial solution. Consider a bit more complicated
example:

local a = Button()
local b = Button()

a:on_click(function() b:some_method() end)
b:on_click(function() a:some_method() end)

Now `a' holds a reference (via "refs" table) to the first anonymous
function, which in turn refers to `b', which holds a reference to the
second anonymous function, which finally refers to `a'. Here we get a
cycle of length 4 instead of 2.

-- Gregory Bonik






--

                                                               Gaspard