简体   繁体   中英

Proper way to manage Lua light userdata

I have a void * to a C++ created object that I pass to Lua using lua_pushlightuserdata() . Lua can perform some actions on that light userdata by passing it to Lua CFunctions and retrieving it with lua_touserdata() . At some point in the future the C++ object is destructed by its owner (C++), memory freed, and set to null. However, Lua still has a reference to this pointer, it doesn't know that it has been destroyed.

Now my Lua functions that take in this userdata make sure the pointer is valid. But what is the best approach for informing Lua that their reference to the light userdata is no longer valid? Do I expose an IsValid(lightuserdata) function to Lua so it can query the status? Or is there a better approach that I am missing.

In my experience I found that it's easier to make Lua own the objects, and you need full userdata to hold the pointer or complete object within userdata memory area. Full userdata can have metatable with __gc metamethod, so objects would be destroyed only after the last reference is garbage-collected on Lua side.

At least don't expose raw pointers to native objects to Lua through lightuserdata , it doesn't really work for native objects lifetime management. Make it some object that is owned by Lua. In simplest case it could be a Lua object (full userdata) holding smart pointer to real native object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM