All pastes #241531 Raw Edit

Miscellany

public text v1 · immutable
·published 2006-11-06 08:40 UTC
rendered paste body
function a(object, params)
	print("calling a, params.x = " .. tostring(params.x))
	params.x = params.x + 0.5
end

function b(object, params)
	print("calling b, params.x = " .. tostring(params.x))
end

function c(object, params)
	print("calling a, params.x = " .. tostring(params.x))
	params.x = params.x * 2
end

function add_hook(object, name, fn, priority)
	local h = {}
	h.name = name
	h.fn = fn
	object.hooks = object.hooks or {}
	object.hooks[priority] = object.hooks[priority] or {}
	object.hooks[priority][#object.hooks[priority] + 1] = h
end

function run_hooks(object, name, params)
	local p = params
	for i, v in pairs(object.hooks) do
		print('Found new priority: (i, v) = (' .. tostring(i) .. ', ' .. tostring(v) .. ')') 
		if (v[1].name == name) then 
			for j, h in ipairs(v) do
				h.fn(object, p)
				if p.quit then break end
			end
			if p.quit then break end
		end	
	end		
end

obj = {}
add_hook(obj, "qwe", a, 100)
add_hook(obj, "qwe", b, 200)
add_hook(obj, "qweqwe", c, 300)
run_hooks(obj, "qwe", {x = 2})