lua-users home
lua-l archive

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


On Fri, Oct 23, 2009 at 11:17 AM, corey johnson <probablycorey@gmail.com> wrote:
> On Fri, Oct 23, 2009 at 10:48 AM, Sam Roberts <vieuxtech@gmail.com> wrote:
>> If you actually need your obj-c code to make lua calls on the
>> userdata, then you need a different
>> system, you need to create a lua table that maps obj-c objects to the
>> userdata they refer to (using
>> lightuserdata). When an obj-c object is released, it will clear the
>> mapping in the lua table. When lua
>> has no mappings, then it will collect the userdata.
>
> Thanks Sam,
> It's a little more complicated than I let on. For a little background,
> I've written an obj-c <-> lua bridge
> http://github.com/probablycorey/wax.
>
> The obj-c code actually calls Lua functions from userdata env, so I
> need to use the userdata as the shared resource. I also currently have
> a table with weak references that links the obj-c object to the
> userdata, but don't have knowledge of when obj-c objects get released.
> This is because I ask obj-c to create objects, I don't have knowledge
> of when it is released. I also pass these objects off to other
> methods, which then control the object's retain/release cycle.

Ok, yes, I see your problem.

obj-c is pretty flexible, you can probably attach a category or
something to your obj-c
objects, dynamically overriding the release message, and calling into
lua land to keep
it apprised of the obj-c ref count. How do other bindings deal with
this? macruby, for example? Do they insert obj-c proxy
objects?

Anyhow, assuming you can't get notified by obj-c when an object is no
longer needed,
then if I understand you correctly, you have essentially implemented a
polling mechanism,
using lua's gc() sweep code, wherein you are attempting to find
userdata that wraps an
obj-c object with a retain count of exactly 1 (which means its only
retainer is lua, and lua
can release it).

Instead of implementing this by hacking the gc, can you make the loop
explicit? Add a poller
to the ns run loop, make a STRONG lightuserdata -> userdata mapping
table, and go through it
periodically, looking for obj-c objects that are only referenced by
lua? If only lua knows about them,
remove them from the strong table, at which point lua's gc will
release them if there are no other refs.

I think all variations of this scheme are actually going to be
heuristic. As long as the object is live in lua it
can come back to life in obj-c, and vice versa.

Cheers,
Sam