"Sputnik" help  
Sputnik Help
Language Reference - Variables - Declaring Static Variables

Declaring Static Variables

Static variables exist in two forms either a function local scope or a class global scope.

In local function scope the static variable can be created only once after that it will ignore all future requests to create it and persist in it's value.

Static locals are stored in a separate table that persists between function calls, unlike regular local variables. This means that functions returning the local variable table as an array may not include static locals. Therefore, when using such functions, it's important to ensure they are designed to handle static locals as well or provide alternative methods to access them.

Example of usage:

Function Cat()
{
    static $meows = 10;
    $meows++;
    say $meows;
}

Cat();
Cat();
Cat();
Cat();
Cat();

// PRINTS
// 11
// 12
// 13
// 14
// 15

Notice how it only gets to 10 once? All the other times the function is called the the = 10 is ignored.

This is useful if you wish to have a variable that is created only once inside a function but does not exist outside of it so it does not clutter the global variable space.

Static variables inside classes are a bit different since they are not based on any local/instance scope and instead are bound to the class itself but not instances of it for example:

class Cat
{
    static $meows = "Meow";
}

say Cat:$meows;

// PRINTS
// Meow

This creates a static variable on the class that can be used and even modified later like so:

class Cat
{
    static $meows = "Meow";
}

say Cat:$meows;
Cat:$meows .= " purr!";
say Cat:$meows;

// PRINTS
// Meow
// Meow purr!
This is useful if you wish to use a class kind of like a namespace to stash variables/functions.

Summary

In Sputnik, static variables can be declared within function local scope or class global scope. Within function local scope, a static variable is created only once and retains its value across subsequent function calls. These static locals are stored in a separate table that persists between function calls, separate from the regular local variables. When accessing the local variable table as an array, it's important to ensure that static locals are handled appropriately.

In class global scope, static variables are bound to the class itself rather than instances of the class. They can be accessed and modified through the class name directly. This allows for using classes as namespaces to store variables and functions.

Overall, static variables in Sputnik provide a way to create variables that exist only within a specific function or class scope, allowing for persistence of values without cluttering the global variable space.


Contact
Cheryl (uberfox@hotmail.com)
Homepage
http://ubersoft.org