2

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.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Nebril
  • 3,153
  • 1
  • 33
  • 50
  • 1
    [debug.setuservalue](http://www.lua.org/manual/5.2/manual.html#pdf-debug.setuservalue) – finnw May 28 '13 at 20:48

2 Answers2

4

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.

W.B.
  • 5,445
  • 19
  • 29
  • Thanks for describing the whole process instead of just giving away the code sample. I decided that I will go with a table for now, as the thing I am trying to do seems to mess up Lua conventions. – Nebril May 29 '13 at 19:38
2

You could use a backing weak table instead:

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

function Class:AttachToUserdataObject(userdataObject)
    _data[userDataObject] = self
end
Eric
  • 95,302
  • 53
  • 242
  • 374
  • I really wish you'd given a more complete example here, I've got a system working with userdata, but now think I'd be better off with a real table backed by a userdata metatable. – Phil Lello Jan 11 '15 at 17:39