Corona SDK Utilities: Chain function

Hello Corona Devs,

I am starting series of tutorial like posts where I will share with all of you some small utility functions for Corona SDK which I use in my apps and games. I have created GitHub repository where I committed all my current utility functions. Please feel free to use/share them. If you find any bugs or have any comments please don’t hesitate to write me.

For my first post I have this small function I called Chain.



function UTL.Chain(...)
	local callbacks = {...};

	return function(...)
		local res = {...};
		for i = 1, #callbacks do
			res = { callbacks[i](unpack(res)) };
		return unpack(res);


What it does

Function Chain take other functions as argument and returns single function: chain function. When chain function called it will start calling first function with arguments it got, then second function with return value of first function, then third function with return value of second and so on. Chain function will return return value of last function.


Here is a small example:

local function Func1(a, b)
	print("Func1 called with ", a, b);
	return a + 1, b + 2;

local function Func2(a, b)
	print("Func2 called with ", a, b);
	return a + b;

local function Func3(a)
	print("Func3 called with ", a);
	return a * 2;

local chain = UTL.Chain(Func1, Func2, Func3);
print("Result is ", chain(1, 1));

Above example will output following:

Func1 called with 	1	1
Func2 called with 	2	3
Func3 called with 	5
Result is 	10


When to use

Chain function is very useful in places where you want to call two functions and don’t want to create a new  anonymous function in place.

For example:

obj:addEventListener("tap", UTL.Chain(PlayTapSound, HideBottomBar, DoSomethingElse));

If you want to return some value from chain: for example you want to return true to stop event layering you can just add function that returns true at the end: in this library there is a function UTL.TrueFn which does that.



Leave a Reply

Your email address will not be published. Required fields are marked *

* Copy This Password *

* Type Or Paste Password Here *