|
Routines and Variable Scoping |
As projects grow, it becomes essential to break code into smaller, reusable building blocks. In Sheerpower, these are called routines. They not only organize your code, but also control how variables are shared, isolated, or reset between calls.
_). For example,
do_taxes is valid, but taxes is not.
Routine names are case-insensitive. By design, Sheerpower
never uses underscores in its own keywords, so your routine
names will never collide with language features.
Global Routines: The default type. All global variables are accessible inside them.
Private Routines: Use their own variable namespace.
By default, variables declared inside are local to that
routine. If you need to access a global variable, prefix it
with main$.
main$ prefix allows
private, scoped, or local routines to access global variables
directly.
Scoped Routines: Similar to private routines, but
all non-static variables are cleared on entry and exit. Prefix
any variable with static to preserve it across
calls.
Local Routines: Defined inside another routine. They share the parent's scope and can only be called from that parent. This makes them ideal for breaking down complex logic into smaller steps without parameter-passing overhead.
Routines always use named parameters. Do
not prefix the call with call.
Instead, write the routine name directly, followed by
with (input) and returning (output)
parameter assignments.
Input parameters in the with clause are
read-only - the compiler prevents any
modifications. They are passed by reference for efficiency,
but cannot be changed within the routine.
Output:
A routine can return up to 16 values using the
returning clause. Each return variable must be
explicitly named in the call.
Sheerpower routines combine clarity, safety, and flexibility. Strong scoping rules reduce accidental variable misuse, while named parameters make code self-documenting and maintainable.
_error and _routine
_error is false on routine entry and becomes
true when you execute set error on; callers
check _error after the call.
Also see the exception handling tutorial.
Inside a routine,
_routine yields the routine’s name as a string.
_).call.
Instead: routine_name with ... returning ...returning;
inputs are passed with the with clause.global – default; shares all
global variablesprivate – separate variable
namespacescoped – like private, but clears
variables on entry/exitlocal – inherits parent's scope;
callable only by parent — aids fast code segmentation_error is false on entry;
set error on marks failure for the caller to check._routine returns the current
routine’s name (string) for debugging/logging.|
Hide Description
|
|
|
Enter or modify the code below, and then click on RUN |
|
Looking for the full power of Sheerpower?
Check out the Sheerpower website. Free to download. Free to use. |