-- hooks.lua -- Joshua's Lua Hack of the Day (JLHotD) for 2007-02-01 -- -- Copyright (c) 2007 Joshua Wise . Use it for -- whatever you like, as long as you credit me if you do. -- -- See http://lua-users.org/wiki/JoshuaWise for a usage example. hooks = {} function hooks:new() local o = {} setmetatable(o, self) return o end hooks.__index = hooks hooks.__magic = {} function hooks:insert(func, weight) local t = { __magic = hooks.__magic, belongsto = self, func = func, weight = weight } table.insert(self, t) table.sort(self, function (a,b) return a.weight < b.weight end) return t end function hooks:remove(t) if t.__magic ~= hooks.__magic or t.belongsto ~= self then error("this table doesn't belong to me!", 2) end for i,v in ipairs(self) do if v == t then table.remove(self, i) end end table.sort(self, function (a,b) return a.weight < b.weight end) end function hooks:__call(...) for k,v in ipairs(self) do v.func(...) end end module"hooks"