lua-users home
lua-l archive

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


Chris Marrin wrote:
I think it would be a mistake not to write code protecting your C functions from disappearing userdata, which by implication can protect you from moving userdata as well. I have had places in my code where I maintained pointers to userdata and it inevitibly caused problems.

I agree with pointer paranoia, but it would be nice to alloc the memory via Lua, so usage is reported correctly. If I understand correctly, a full userdata is simply a block of memory that is returned by the Lua allocator (malloc/realloc by default). It may well start below the pointer we get, but the pointer should stay valid until the ud is gc'ed.

Now I
let Lua maintain the pointers and I simply have references into the Lua VM. I either use the registry or similar tables. The __gc metamethod can keep you fully informed about the lifetime of each userdata. And Lua has a powerful feature for maintining weak pointers to avoid frozen userdata pointers. When attempting to get a reference to a weak pointer you will get back a nil so you can cleanly handle this case. All these techniques keep your C state consistent with your Lua state.

That would actually be worse than lightuserdata in my current scenario. I currently remove blocks from my Lua "free list", and assign them to a field in another userdata object. If they are full userdata, I need to keep a reference to them in Lua (a "busy list"), so they are not collected. This is worth doing if I can use a full userdata as the buffer directly, but if I'm allocing and freeing them anyway, boxing the pointer doesn't gain me much.
Although I may be able to replace the free list with a weak table....

I'll probably re-think it later, when I've got the rest of this lib working.
It is the sort of thing that can easily be reworked later.

I think one of Lua's most powerful and useful features is its simple yet flexible C interface.

Hear Hear.
We have the luxury of choosing between light and full userdata, boxed pointers, etc. I'm drifting toward having an embedded Lua vm in _everything_, for general string handling and hashmap/array storage.

Adrian