3

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.

Moop
  • 3,414
  • 2
  • 23
  • 37

1 Answers1

2

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.

Vlad
  • 5,450
  • 1
  • 12
  • 19