[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Better Syntax?
- From: Martin <eden_martin_fuhrspam@...>
- Date: Mon, 3 Oct 2016 16:46:47 -0700
On 16-10-03 03:43 AM, Mike Jones wrote:
> Hi,
>
> I am working on a project where I have basically an event style
> framework, and I would like some way to "chain together" functions.
>
> Here is a short example of what I am doing at the moment:
>
> -- core function, defined in common header
> function dosomething(arg)
> print("Orginal dosomething()")
> return 0
> end
>
> -- module 1 included in script, adds extra code on to existing function
> pre_module1_dosomething = dosomething
> function dosomething(arg)
> print("Module 1 dosomething()")
> return pre_module1_dosomething(arg)
> end
>
> In my example the functions are in different files, but that's the
> basic pattern I am currently using to chain extra code on to the end
> of a function that has already been defined. When executed it should
> output "Module 1 dosomething()" followed by "Original dosomething()",
> ie both functions get executed. Is there a better way of achieving
> this sort of functionality? the use of the "pre_module1_dosomething"
> variable to hold the parent function seems very ugly to me.
Hi,
I don't see problems in original approach. I'd just change
"pre_module1_dosomething = dosomething" to
"local pre_module1_dosomething = dosomething" to avoid spoiling
_G table.
The other way may be introducing global functions like
"_G.register_callback(method_name, func)"
which stores handler function of given method and
"_G.handle_event(method_name, ...)"
which sequentially calls all handlers for given method
and returns result of handler which was registered first
(or first not nil result - anything you choose)
so in in header file code should be like
register_callback(
'dosomething',
function(arg)
print('Orginal dosomething()')
return 0
end
)
in module 1:
register_callback(
'dosomething',
function(arg)
print('Module 1 dosomething()')
end
)
And in users code:
handle_event('dosomething', ...)