Reflection

A library for allowing a script to look at itself and perform introspective tasks.

This library gives a script access to itself.

Reflection is a concept where a program can examine itself and its current state while running. This may also include the ability to access, edit or manipulate features.

Reflection is dangerous by nature.

The program is not in a constant state and so, when accessing parts reflectively, the programmer must anticipate what could be happening at any time.

Variables

The variables function returns the current environment's variable container.

This object acts like a key<->value map, where the keys are the variable names and the values are the variable values.

import [reflection]

number = 10
assert number == 10

variables = run reflection[variables]
assert variables[number] == 10

variables[number=5]
assert number == 5

This object is the variable container. Changes to the container are immediately reflected in the variables available.

Storing the container in a variable means the container contains itself.

import [reflection]

variables = run reflection[variables]
assert variables == variables[variables]

This can be used to pass the entire variable environment to a function, essentially running its code in the same environment.

Passing the environment to another function or process is not advised and can lead to variable pollution and data corruption.

import [reflection]

number = 10
word = "hello"

func = function {
    number = 5
    word = "there"
}

run func run reflection[variables]

assert number == 5
assert word == "there"

Line

The line function returns the current line being executed.

import [reflection]

line = run reflection[line]

Script

The script function returns the current script being executed.

This allows code to retrieve a script object without knowing its name.

import [reflection]

script = run reflection[script]
/print currently running {script}

Inside a function or other anonymous executable the script will be wherever that process was started from.

Root

The root function returns the original script that was run.

import [reflection]

script = run reflection[root]
/print we started at {script}

The root script is wherever the current program started, e.g. a script that was run from a command.

Interpolate

The interpolate function attempts to parse interpolations in a text based on the current environment.

A text containing the { and } interpolation brackets is converted to a formatted version, with the statements inside the brackets having been executed.

import [reflection]

word = "there"
text = "hello {" + "word}"

result = run reflection[interpolate] text

assert result == "hello there"
assert text != "hello there"

Last updated