lua-users home
lua-l archive

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

在 2017/3/8 1:11, pierre 写道:
> Hi,
> How can I interact with the lua gc from the C API? What am I looking for
> is not how to launch or block the gc of lua, but how can I tell lua,
> from the API, that a resource is being used?

just store it somewhere the collector can reach, e.g. on the stack or into some table. typically the registry is supposed to be used by the C side for such usages.

> For example, while binding a GUI library, a button can have an image
> attached. The image and the button are userdata type, both created in
> lua (via the C API), but the image is linked to the button also via the
> C API. so, lua has no way to know that the image cannot be freed because
> linked to another object outside of its control.
> How can I tell lua the resource is being used and then no more used
> (block from gc or ready for gc)?

a userdata is an opaque object for Lua, but Lua provide a mechanism called uservalue for this usecase. you can also (ab)use the metatable if each userdata object use dedicated metatable (instead of sharing metatable across all instances of same type userdata)

> may be add an entry "c_linked" of type table to the metatable of the button; and in this table,
> add an entry per field and linked it the userdata that is attached to it so that lua sees a link?
> should work, no?

this could work, you need to use weak key so that the map table won't keep the actual button userdata from being collected.

the nerdy Peng / 书呆彭 /