Cobra Inline Programs user-defined functions


user-defined functions


declarations: function name ( [formal parameters] ) { ... }
function calls: name ( [actual parameters] )


The function keyword can be used to define new functions, e.g. as in:
	function name(par1, par2) {
		. = .nxt;
		if (.txt == par1)
		{	return par2;
		return 0;
where parameters (which are optional) are passed by value. The basename of an associative array cannot be passed as a parameter, since that would require copying its entire contents. When needed, it is better to make the array global in this case. (There are only two levels of scope in the scripting language: global or function local.)

The return can be used in function definitions to return any type of value. As elsewhere, the types of parameters or of the return type of the function does not need to be provided, but is deduced from context.

Any inline program fragment can be used inside a function definition. Variable names used are first checked to see if they are global variables, with values that persist across function call boundaries. If not global, they are considered function local variables that disappear at the end of the function execution.

Functions can be recursive, as in the following example:

		function factorial(val)
			if (val <= 1)
			{	return 1;
			return val * factorial(val-1);
		print "5! = " factorial(5) "\n";
A few things are worth pointing out. First, note that all statements must be terminated by a semi-colon. Second, the body of an if, else, while, and for statement must always be enclosed in curly braces. Third, if you forget to test the value of the parameter in the code above, the recursion will clearly not be bounded, and Cobra will report a stack overflow error when the maximum depth of the recursion is exceeded. Fourth, and finally, if you forget to end the program above with a Stop command, the calculation will be repeated, and the result reported, once for every token in the input sequence.

Function definitions have global scope, and when given in one program fragment, they can be used (called) in all susequent program fragments. A function definition cannot be deleted, other than by restarting the Cobra session itself, but they can be redefined.

It is easy to debug online programs, with or without function definitions, by adding selected print statements, as in other programming languages.

Inline Programs
(Last Updated: 11 May 2019)