User Function

From Sputnik Wiki
(Difference between revisions)
Jump to: navigation, search
(Function Rules)
(Remarks)
 
(10 intermediate revisions by one user not shown)
Line 10: Line 10:
  
 
=== Features ===
 
=== Features ===
 +
 +
=== Embedding ===
 +
 +
A class can be embedded inside an IF statement (or any statement) so that it can be created on a conditional for example:
 +
 +
<syntaxhighlight lang="sputnik">
 +
// Check if the function already exists and
 +
// if it does already exists don't create it
 +
if (!FunctionExists("Cat"))
 +
{
 +
// Create the function using the Embedded keyword
 +
Embedded Function Cat()
 +
{
 +
say "testy!";
 +
}; // note ; is required here
 +
}
 +
Cat();
 +
// PRINTS
 +
// testy!
 +
</syntaxhighlight>
  
 
=== Remarks ===
 
=== Remarks ===
Line 16: Line 36:
  
 
==== Important Examples ====
 
==== Important Examples ====
 +
 +
===== Parameters as pointers =====
 +
 +
You can pass variables as a pointer to a function so the function can modify them variables directly rather than work on a copy of them.
 +
 +
The only real benefit of doing this is it speeds up execution time by not having to copy the variable.
 +
 +
This is only useful when used on arrays especially very big arrays.
 +
 +
To make a pointer you use & like in C++ and place it in parameter section of the function.
 +
 +
<syntaxhighlight lang="sputnik">
 +
// Make a string
 +
my $MyString = "Hello";
 +
 +
// Print it
 +
say $MyString; // Prints "Hello"
 +
 +
// Fail to modify it
 +
Test($MyString);
 +
 +
// Print to prove fail
 +
say $MyString; // Prints "Hello"
 +
 +
// Correctly modify it
 +
Test2($MyString);
 +
 +
// Print modified string
 +
say $MyString; // Prints "Hello world!"
 +
 +
// A function that does not use a pointer
 +
// so any modifications to the variable
 +
// do not leave the function since it is
 +
// only playing with a *copy*
 +
Function Test($str)
 +
{
 +
$str .= " world!";
 +
}
 +
 +
// A function that does use a pointer so
 +
// any modifications that take place do
 +
// indeed change the variable
 +
Function Test2(&$str)
 +
{
 +
$str .= " world!";
 +
}
 +
</syntaxhighlight>
  
 
===== Unlimited Function Parameters =====
 
===== Unlimited Function Parameters =====
Line 21: Line 88:
 
If you’ve most likely noticed that several function such as println() can take an indeterminate number of arguments. Normally when defining a function you specify each argument in the function declaration. Obviously it would be impossible to define an infinite number of arguments in such a way. Sputnik does, however, allow you to accomplish this through the array @args.
 
If you’ve most likely noticed that several function such as println() can take an indeterminate number of arguments. Normally when defining a function you specify each argument in the function declaration. Obviously it would be impossible to define an infinite number of arguments in such a way. Sputnik does, however, allow you to accomplish this through the array @args.
  
@args is an array consisting of all of the arguments passed to a function. Using this method you can bypass the conventional method of defining parameters in the function definition all-together. Here is an example:
+
@args is an array consisting of all of the arguments passed to a function. Using this method you can bypass the conventional method of defining parameters in the function definition all-together.
 +
 
 +
However @args is not created by default and you must activate it if you wish to use it.
 +
 
 +
Here is an example:
  
 
<syntaxhighlight lang="sputnik">
 
<syntaxhighlight lang="sputnik">
 
println( Add(1, 2, 3) ); // will return 6
 
println( Add(1, 2, 3) ); // will return 6
  
 +
// Allow the @args variable to be made (we will use it)
 +
// you place this above a function to allow @Args
 +
// the reason is becaus the creation of @Args involves
 +
// creating an array and pushing items onto it etc and
 +
// can use a tiny bit of processing power so we don't do
 +
// it unless we want to do it
 +
[Args("true")]
 
Function Add()
 
Function Add()
 
{
 
{
Line 42: Line 120:
  
 
Note - If outside a function @args will return an empty array.
 
Note - If outside a function @args will return an empty array.
 +
 +
Since @args exists it is possible to use that as the function parameters... Example
 +
<syntaxhighlight lang="sputnik">
 +
doMsg("Hello", 777);
 +
 +
[Args("true")]
 +
Function doMsg()
 +
{
 +
my List( $msg, $code ) = @args;
 +
echo "$msg | $code"; // Prints: Hello | 777
 +
}
 +
// This tends to work very similar to the @_ in perl
 +
</syntaxhighlight>
  
 
===== Function Rules =====
 
===== Function Rules =====
Line 50: Line 141:
 
<pre>
 
<pre>
 
TYPE                  WHAT IT DOES
 
TYPE                  WHAT IT DOES
Args                  Allows disabling the creation of @ARGS variable
+
Args                  Allows enabling the creation of @ARGS variable
 
Returns                Forces a specific return type to the function
 
Returns                Forces a specific return type to the function
 
                       (gives exception if wrong type is given)
 
                       (gives exception if wrong type is given)
Line 56: Line 147:
 
Override              Overrides a CORE function with this name and forces all
 
Override              Overrides a CORE function with this name and forces all
 
                       call to that function to route to you function instead
 
                       call to that function to route to you function instead
ShowLink              Allows creation of @IsLink macro for this function this can
+
</pre>
                      be used to find out if this function is a Test($a) call or a
+
 
                      $a->Test() call
+
Default for the rules
 +
<pre>
 +
TYPE                  DEFAULT
 +
Args                  FALSE
 +
Returns                <totally disabled>
 +
ReturnCast            <totally disabled>
 +
Override              FALSE
 
</pre>
 
</pre>
  
Line 66: Line 163:
 
<syntaxhighlight lang="sputnik">
 
<syntaxhighlight lang="sputnik">
 
// The @Args variable is a special variable
 
// The @Args variable is a special variable
// that exists in all functions it is used to
+
// that can be used in any function it is used to
 
// handle infinite params the same as perls @_
 
// handle infinite params the same as perls @_
// parma 0 is @Args[0] and so on...
+
// param 0 is @Args[0] and so on...
// of course making this array if its not going
+
// If you wish to use infinite parameters thenb
// to be used might slow your program down a
+
// you must enable this rule.
// few minor microseconds so you can remove it
+
// if you want using this rule.
+
 
println("### First no rule");
 
println("### First no rule");
 
Test("Cat", "Dog");
 
Test("Cat", "Dog");
Line 78: Line 173:
 
TestWithRule("Cat", "Dog");
 
TestWithRule("Cat", "Dog");
  
// A test function with no rules so @args should be created
+
// A test function with no rules so @args should NOT be created
 
Function Test($a, $b)
 
Function Test($a, $b)
 
{
 
{
Line 87: Line 182:
  
 
// This function is same as above but this time with the rule
 
// This function is same as above but this time with the rule
[Args("false")]
+
[Args("true")]
 
Function TestWithRule($a, $b)
 
Function TestWithRule($a, $b)
 
{
 
{
Line 94: Line 189:
 
printr(@args);
 
printr(@args);
 
}
 
}
// Notice the test with the rule had no @args variable at all?
+
// Notice the test without the rule had no @args variable at all?
// This can useful if this function gets called millions of times
+
// and you want to squeeze every ounce of speed out of it
+
 
</syntaxhighlight>
 
</syntaxhighlight>
  
Line 148: Line 241:
 
// cores and suddenly find it does not exist and behave in weird and/or
 
// cores and suddenly find it does not exist and behave in weird and/or
 
// disastrous way.  
 
// disastrous way.  
</syntaxhighlight>
 
 
Example of using Rule: ShowLink
 
<syntaxhighlight lang="sputnik">
 
// With no link
 
$a = "Test";
 
$ret = Test($a);
 
say $a; // Prints Test
 
say $ret; // Prints Pest
 
 
// With link
 
$a = "Cat";
 
$a->Test();
 
say $a; // Prints Pat
 
 
[ShowLink("true")] // Allow creation of @IsLink
 
Function Test( &$a ) // Ref the $a so we can deal
 
{                    // with the real one directly
 
// True if the user used $a->Test()
 
if(@IsLink['a'])
 
{
 
// Edit the original
 
$a[0] = 'P';
 
}
 
// Else this is a normal Test($a) call
 
else
 
{
 
// Return a modified string
 
return 'P' . SubStr($a, 1);
 
}
 
}
 
// This rule is needed to find out if the user is calling
 
// the function by:
 
// Test($a)
 
// OR
 
// $a->Test()
 
// You might wonder why that matters well $a->Test() is
 
// better to modify the variable in place and
 
// Test($a) is better used to return a modified copy instead
 
 
</syntaxhighlight>
 
</syntaxhighlight>
  
Line 224: Line 278:
  
  
 +
In this example we dont include the ( ) on the function and by not including it the function will automatically assumes you plan to use the @args variable and will enable it for you
  
 
<syntaxhighlight lang="sputnik">
 
<syntaxhighlight lang="sputnik">
 
Test("CAT", 111);
 
Test("CAT", 111);
 
 
Function Test
 
Function Test
 
{
 
{
Line 234: Line 288:
 
};
 
};
 
</syntaxhighlight>
 
</syntaxhighlight>
 +
 +
[[Category:User Defined Functions]]

Latest revision as of 10:08, 20 September 2015

Function <name> ( <Parameters> ... )
{
	statements
	...
}

Contents

Description

Features

Embedding

A class can be embedded inside an IF statement (or any statement) so that it can be created on a conditional for example:

// Check if the function already exists and
// if it does already exists don't create it
if (!FunctionExists("Cat"))
{
	// Create the function using the Embedded keyword
	Embedded Function Cat()
	{
		say "testy!";
	}; // note ; is required here
}
Cat();
// PRINTS
// testy!

Remarks

Examples

Important Examples

Parameters as pointers

You can pass variables as a pointer to a function so the function can modify them variables directly rather than work on a copy of them.

The only real benefit of doing this is it speeds up execution time by not having to copy the variable.

This is only useful when used on arrays especially very big arrays.

To make a pointer you use & like in C++ and place it in parameter section of the function.

// Make a string
my $MyString = "Hello";
 
// Print it
say $MyString; // Prints "Hello"
 
// Fail to modify it
Test($MyString);
 
// Print to prove fail
say $MyString; // Prints "Hello"
 
// Correctly modify it
Test2($MyString);
 
// Print modified string
say $MyString; // Prints "Hello world!"
 
// A function that does not use a pointer
// so any modifications to the variable
// do not leave the function since it is
// only playing with a *copy*
Function Test($str)
{
	$str .= " world!";
}
 
// A function that does use a pointer so
// any modifications that take place do
// indeed change the variable
Function Test2(&$str)
{
	$str .= " world!";
}
Unlimited Function Parameters

If you’ve most likely noticed that several function such as println() can take an indeterminate number of arguments. Normally when defining a function you specify each argument in the function declaration. Obviously it would be impossible to define an infinite number of arguments in such a way. Sputnik does, however, allow you to accomplish this through the array @args.

@args is an array consisting of all of the arguments passed to a function. Using this method you can bypass the conventional method of defining parameters in the function definition all-together.

However @args is not created by default and you must activate it if you wish to use it.

Here is an example:

println( Add(1, 2, 3) ); // will return 6
 
// Allow the @args variable to be made (we will use it)
// you place this above a function to allow @Args
// the reason is becaus the creation of @Args involves
// creating an array and pushing items onto it etc and
// can use a tiny bit of processing power so we don't do
// it unless we want to do it
[Args("true")]
Function Add()
{
	my $Total = 0;
	foreach( @args as my $item )
	{
		$Total += $item;
	}
	return $Total;
}

If for whatever reason you need to know the total number of arguments passed to a function, You can simply use Count($args) within the function.

When retrieving arguments in this manner it is important to remember that @args only contains an array of arguments passed by the user. It does not account for default values etc.

Note - If outside a function @args will return an empty array.

Since @args exists it is possible to use that as the function parameters... Example

doMsg("Hello", 777);
 
[Args("true")]
Function doMsg()
{
	my List( $msg, $code ) = @args;
	echo "$msg | $code"; // Prints: Hello | 777
}
// This tends to work very similar to the @_ in perl
Function Rules

You can add special rules to your function to tell it how to operate using the [] brackets before the word "Function".

Here is a list of the possible rules:

TYPE                   WHAT IT DOES
Args                   Allows enabling the creation of @ARGS variable
Returns                Forces a specific return type to the function
                       (gives exception if wrong type is given)
ReturnCast             Casts all return values to this type if it is not already
Override               Overrides a CORE function with this name and forces all
                       call to that function to route to you function instead

Default for the rules

TYPE                   DEFAULT
Args                   FALSE
Returns                <totally disabled>
ReturnCast             <totally disabled>
Override               FALSE

For a list of data type to use with Returns/ReturnCast see HERE.

Example of using Rule: Args

// The @Args variable is a special variable
// that can be used in any function it is used to
// handle infinite params the same as perls @_
// param 0 is @Args[0] and so on...
// If you wish to use infinite parameters thenb
// you must enable this rule.
println("### First no rule");
Test("Cat", "Dog");
println("### Now with rule");
TestWithRule("Cat", "Dog");
 
// A test function with no rules so @args should NOT be created
Function Test($a, $b)
{
	println("\$a: $a \$b: '$b'");
	println("\@args[0]: @args[0] \@args[1]: '@args[1]'");
	printr(@args);
}
 
// This function is same as above but this time with the rule
[Args("true")]
Function TestWithRule($a, $b)
{
	println("\$a: $a \$b: '$b'");
	println("\@args[0]: @args[0] \@args[1]: '@args[1]'");
	printr(@args);
}
// Notice the test without the rule had no @args variable at all?

Example of using Rule: Returns

print(vardump(Test(true)));
print(vardump(Test(false)));
 
[Returns("bool")]
Function Test( $returnBool )
{
	if($returnBool)
		return 1 == 2;
	else
		return "Hello";
}
// This forces this function to require a bool to be returned
// if a bool is not returned it will throw an exception instantly
// it will not try to convert the return to a bool

Example of using Rule: ReturnCast

[ReturnCast("bool")]
Function Test( $returnBool )
{
	if($returnBool)
		return 1 == 2;
	else
		return 1;
}
// This forces this function to return a bool no matter what
// It will even return the default value (0 for ints, false for bool etc)
// if it cannot convert or find a return value at all
// If there is a return value it will converted to a bool

Example of using Rule: Override

Print("Moo moo farm");
 
[Override("true")]
Function Print()
{
	say "HELLO?!?!??";
}
// This forces all calls to Print() (core) function to go to your
// function instead this can prove useful if you are extending
// the functionality of a core function.
// Be careful however since Sputnik might want to call one of the
// cores and suddenly find it does not exist and behave in weird and/or
// disastrous way.

General Examples

println( Add(1, 2) ); // will return 3
 
Function Add($a, $b)
{
	return $a + $b;
}


println( Add(2) ); // will return 52
println( Add(2, 4) ); // will return 6
 
Function Add($a, $b = 50)
{
	return $a + $b;
}


println( Add() ); // will return 60
println( Add(2) ); // will return 52
println( Add(2, 4) ); // will return 6
 
Function Add($a = 10, $b = 50)
{
	return $a + $b;
}


In this example we dont include the ( ) on the function and by not including it the function will automatically assumes you plan to use the @args variable and will enable it for you

Test("CAT", 111);
Function Test
{
	my List ($Name, $Password) = @args;
	println("Name '$Name' Password '$Password'");
};
Personal tools
Namespaces
Variants
Actions
Navigation
Toolbox