Tinderbox v9 Icon

Variable use in functions

Important note: all examples follow aTbRef naming conventions.


Defining a variable in a function

A variable is defined exactly the same way as in other action code:

var vThing; 

As the basic assumed data type, if not set, is a String, it can be more helpful to use explicit typing, whether or not a value is applied straightway. The point is that the variable has a notified data data from the outset, rather than one coerced by Tinderbox based on context of use:

	var:string vThing;
	var:number vCount;
	var:date vNow = date("today");
	var:boolean vBoolean = true;

A variable needs to be defined before first use, as with attributes. It makes good sense to define variables (unless only used inside loops) at the start of the function. Do consider also adding comments., as once written the code may only be re-read occasionally and the code's intent may get forgotten over time.)

Using variables to set data type of inputs

As function arguments are received as assumed String-type, it can be useful to set a data type before using the argument value in the functions action code:

	function fMakeTable(iSomeList){
		var:list vList = iSomeList;
		vList.each(anItem){
			// ... etc.
	}

Variable duration

Variables created in a function are destroyed when the function execution completes. If a variables value is needed, other than as a return value, the value will need to be passed to an attribute for more persistent storage.

	// ...
	$MyString = vString;
	$SomeNumber ("config-note") = vCount;
	// ...

In the first case, $MyString in the calling note is set. In the latter case, $SomNumber is note "config-note" is set. The choice of where a stored value is saved is dependent on the wider context of use, i.e. there is n single 'correct' choice.

A variable may be used as an input argument for a call to another function:

	// ...
	var:string vString = "Testing!";
	fAnotherFunction(vString){
	 // ...

Variable scope

A variable created in a function is only accessible from within that same function. For experience programmers this may seem unexpected (see more) and may chance in the future. At present, a varaible should only be called within the function in which it is defined.


Next: Variable use in functions