lua-users home
lua-l archive

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


1.  Is it safe to assume that Lua will free the memory that is allocated 
by lua_newuserdata(), if I do nothing more than this?

Yes.

2.  Are there any caveats that I should be aware of when letting Lua free 
the allocated block, especially in the realm of C++?  IE, if I put a class 
in my struct, will the destructor be called, etc?

No. The memory is allocated with malloc, not new. Neither constructors nor 
destructors will be called.

3.  If lua_newuserdata() returns NULL, what can I assume about the stack? 
Does anything get pushed onto the stack in the case of a failure?

That something horribly wrong has happened. lua_newuserdata throws an 
error on failure (defined as the underlying malloc implementation 
returning 0); the only way it would return NULL itself is if the lua_State 
object it is being passed is NULL.

4.  Are there any sample programs out there that detail how to set a GC 
metamethod so I can try and free my own memory?  Is there a general rule 
for when you should and should not free your own memory?

You should never free memory which Lua has allocated. You should always 
free memory which you have allocated. (Lua never "takes" or "gives" 
ownership of memory. If you have a call to malloc() or free, you need a 
matching call to free() or delete. Or whatever you use to allocate 
resources.) It is really that simple.

If you want to handle your own memory, use the userdata only to hold a 
pointer to an object you have allocated.

Hope this helps.

R.