Question

I have a function in lua that accepts a userdata object.

function Class:AttachToUserdataObject(userdataObject)
  userDataObject.tableAttached = self
end

But later on, when I am using the same userdata object, I can't find it - userdataObject.tableAttached is nil. I feel like I don't fully understand the way userdata objects work yet.

Is there any way of binding the object to userdata other than creating a global table that has ids of all userdata objects (they have unique id) and references to tables?

I would like to keep it as elegant as I can, but without the access to C++ code I guess I can sacrifice some elegancy if it just works.

Was it helpful?

Solution

A userdata object does not have fields like a table and Lua has no knowledge whatsoever about internals of the underlying C object. In order to achieve what you want, you'd have to handle the __index and __newindex metamethods.

So, for example, when doing the assignment like userdataObject.tableAttached = self, the __newindex metamethod is triggered. Inside it, you could just store the value in the metatable itself (subject to a possible name collision) or in another table, which itself is stored in the metatable.

To retrieve the data back, you'd have to handle the __index metamethod. It can get a bit tricky with userdata, so let me know, if you run into problems.

OTHER TIPS

You could use a backing weak table instead:

local _data = setmetatable({}, {__mode='k'})

function Class:AttachToUserdataObject(userdataObject)
    _data[userDataObject] = self
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top