Search code examples
c++pointerslualua-userdata

Delete all of my Lua userdata in C++


I'm wondering if it's possible to access all of the userdata "tables" (is it called userdata tables?) and then delete them from Lua because this is my problem:

a = Object(5, 5)
a:Delete()
a:SetPosition(3,3)

As you can see first I create an object and save an pointer to a c++ class called Object which is allocated using "new" in my map class. Then I delete the object which means I delete the allocated memory for the pointer in my map class. And last I call SetPosition, if the memory still is allocated for the c++ Object class everything will run fun. But if it is deletes (as it is in this case because we called Delete() before the SetPosition(...) call) my program will crash. So what I'm wondering is following:

Is it possible to set the varaible 'a' in lua to nil by calling Delete ? I know I could do something like 'a = a:Delete()' if Delete return nil but if I forget to do the 'a =' part it fail. Also I'm wondering if it's possible to delete the userdata and check if it doesn't exist when I call SetPositon(), if it doesn't I will just return.

Also, the base code is from: http://lua-users.org/wiki/SimpleCppBinding


Solution

  • In the Delete method, set the metatable of the received object to nil and you'll get an error message if you later call a method on that object.