Revision [720]

This is an old revision of FunctionPurity made by AdminSkyld on 2010-06-02 16:10:35.
 

Function Purity


A "pure" function is one that takes some input and returns some output without having any side effects (essentially, the state of the script should be exactly the same after running the function, meaning any this, player or other global variables should not be changed, no output should be made apart from it's return value, etc). For example:

function example_pure(temp.a)
{
	temp.b = temp.a * 2;
	return temp.b + 2;
}

A pure function should always give the same output given the same input values. For instance, the above function will always return 14 if you give it the input value 6. Typically this means that a function:

Here are some built-in examples of pure functions: sin(x), str.length().

An "impure" function is one that may give a different output on the same input, or has side effects, e.g.

function example_impure(temp.a)
{
	player.chat = "Impure!!";
	return temp.a + 2;
}

This function is impure because the script has changed something outside of the function, in this example, player.chat.

Here are some examples of built-in impure functions: echo(x), random().

Generally, a good way to make clearer code is to have as many pure functions as possible, and only have the impure function be all the way at the outside of your pure function calls.

Categories

CategoryMiscellaneous

There are no comments on this page. [Add comment]

Valid XHTML 1.0 Transitional :: Valid CSS :: Powered by WikkaWiki