(02-15-2012, 12:24 AM)xoft Wrote: Callbacks are a great way of doing things, though I'd prefer class-callbacks (see cWorld::ForEachPlayer() for an example). Instead of passing a function pointer, you pass a pointer to a class that has overridden a specific virtual method that does the actual work. The advantage is that the class can carry more data (parameters, accumulators etc), the disadvantage is that probably this won't work with Lua (I have no idea).
It _can_ work with Lua, unforunately even though Lua can work with objects, Lua itself is not really object orientated and has some extremely basic object inheritance.
To inherit objects you need to write some really ugly code like this:
Code:
local ChatLogPlugin = {}
ChatLogPlugin.__index = ChatLogPlugin
function ChatLogPlugin:new()
local t = {}
setmetatable(t, ChatLogPlugin)
local w = Lua__cPlugin:new()
tolua.setpeer(w, t)
w:tolua__set_instance(w)
return w
end
Here ChatLogPlugin practically inherits cPlugin by having Lua__cPlugin forward calls to the Lua object. But I don't like it because it requires this piece of code, it's confusing and ugly.
I think we simply need special implementations of those ForEach* functions to work with Lua function callbacks. I don't think the carrying more data is an issue in Lua, because you can simply store that data externally somewhere, or supply an additional Lua table to the function.
Code:
local SayHiData = 0
function Initialize( Plugin )
cRoot:Get():GetWorld():ForEachPlayer( SayHi, SayHiData )
return true
end
function SayHi( Player, Data )
SayHiData = SayHiData + 1
Player:SendMessage("Hi player ".. SayHiData .. "!")
end
In this example it sends a number along, but it could also send a table reference with much more data. So you could say that SayHiData is the class instance, and it could even be made an optional parameter.