CodeSmile
CodeSmile

Reputation: 64477

How to implement (anonymous) Lua callback functions for any number of Lua objects (tables)?

I have "objects" in Lua which use a table to maintain their set of data and functions. Simple example:

obj = {func = function(self) print(self) end}

There may be any number of objects.

Now I have a C function registerObject(obj) which should somehow keep a reference to that Lua object (obj table) in order to be able to call that particular object's func function (and others) at a later time. That means I don't have a name for the object's table, I somehow need to keep a reference to the table itself.

How can I make this work? C++ example also acceptable, in fact the C function is merely an interface that creates an Objective-C class for each obj.

Upvotes: 0

Views: 993

Answers (2)

sbk
sbk

Reputation: 9508

The registry. I have nothing more to say

Upvotes: -1

jpjacobs
jpjacobs

Reputation: 9549

Lua tables are passed by reference, so they are actually always "Anonymous", with a reference to them stored in a variable. I'd just put all your "objects" in a table like this:

objects={}
function registerObject(obj)
    objects[#objects+1]=obj
end
a={func=function(self) return(self.data) end, data='foo'}
b={func=function(self) return(self.data) end, data='bar'}
registerObject(a)
registerObject(b)
for k,v in pairs(objects) do
    print("Object",k,"data:",v:func())
end

One thing you need to keep in mind is that this inhibits collection of those tables, since there always is a reference to the objects in the objects table, unless you explicitly delete it. This might or might not be what you want. If you do not want the objects table to interfere with garbage collection, you can set its __mode entry in the metatable to 'v' for weak values. That way, the references to the object in the objects table aren't counted; if the value in the objects table is the only remaining reference to the object, the object will be collected (See Programming in Lua for more info).

Upvotes: 2

Related Questions