Difference between revisions of "Outer"
(fixed formatting problems and bug in example code) |
|||
Line 1: | Line 1: | ||
− | The <c>outer</c> intrinsic function gets a reference to the variables of the enclosing scope. In the case of nested functions, it's the variables local to the function in which | + | The <c>outer</c> intrinsic function gets a reference to the variables of the enclosing scope. In the case of nested functions, it's the variables local to the function in which the nested function was defined. In an [[import]] module, it can be used to access the module scope (similar to "file scope" in some other languages). If called in an ordinary, non-nested function defined at the global scope, then <c>outer</c> is equivalent to <c>[[globals]]</c>. |
See also: [[globals]]; [[locals]]. | See also: [[globals]]; [[locals]]. |
Latest revision as of 13:37, 29 October 2022
The outer
intrinsic function gets a reference to the variables of the enclosing scope. In the case of nested functions, it's the variables local to the function in which the nested function was defined. In an import module, it can be used to access the module scope (similar to "file scope" in some other languages). If called in an ordinary, non-nested function defined at the global scope, then outer
is equivalent to globals
.
Example
Many of the modules in /sys/lib
run unit tests. The runUnitTests
function defines several a helper function, assertEqual
inside it. This function checks for errors, but also needs to maintain an error count across calls. So it uses outer
to update an error count defined at the level of the enclosing function, runUnitTests
:
runUnitTests = function()
errorCount = 0
assertEqual = function(actual, expected)
if actual != expected then
print "Unit test failure: expected " + expected + ", got " + actual
outer.errorCount = errorCount + 1
end if
end function
assertEqual 2+2, 5
end function
runUnitTests