Functionally Equivalent Language Translation →
(defstatic var-name [initial-value-expression]) (defstatic cache (array)) ; create a cached array (defstatic count 0) ; initialise a function counter
See also DEFVAR = / ASSIGN
This instruction asks that the named variable be of a type that maintains its state across invocations of a file unit or function call. **An optional initial value* may be supplied. If not initial value is given then the default behaviour is unspecified by FELT; it is the behaviour of the chosen target back-end language that will dictate what happens at execution time.
Some but not all languages allow the concept of "static" variables such that within a particular scope, be it file or functional, that variable maintains whatever state state it has across invocations of a function.
This allows functions to be able to implement simple cache or memoization behaviours as the "static" variable does not get re-set each time the function is called.
The following FELT code shows how you might use DEFSTATIC
variable within the scope of a function to maintain a list of results: this is a very simple memoization scheme and, at the expense of memory it will provide faster response times:
(defun do-query(query-string) (defstatic cache []) (defvar hash (md5 query-string)) (if (isset (@ cache hash)) (return (@ cache hash))) ;; first time here, do it... (= (@ cache hash) (execute-query query-string)) (return (@ cache hash)))
The rendered PHP code for the above example is:
function do_query($query_string) { static $cache = array(); $hash = md5($query_string); if (isset($cache[$hash])) { return $cache[$hash]; } $cache[$hash] = execute_query($query_string); return $cache[$hash]; }
JavaScript does not have this feature and just defines a normal locally scoped variable instead.
function do_query($query_string) { static $cache = array(); $hash = md5($query_string); if (isset($cache[$hash])) { return $cache[$hash]; } $cache[$hash] = execute_query($query_string); return $cache[$hash]; }