Difference between revisions of "Outer"
(Created page with "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 whic...") |
|||
(One intermediate revision by the same user not shown) | |||
Line 1: | Line 1: | ||
− | The | + | 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]]. | ||
Line 5: | Line 5: | ||
== Example == | == Example == | ||
− | Many of the modules in | + | Many of the modules in <c>/sys/lib</c> run unit tests. The <c>runUnitTests</c> function defines several a helper function, <c>assertEqual</c> inside it. This function checks for errors, but also needs to maintain an error count across calls. So it uses <c>outer</c> to update an error count defined at the level of the enclosing function, <c>runUnitTests</c>: |
<ms>runUnitTests = function() | <ms>runUnitTests = function() | ||
Line 11: | Line 11: | ||
assertEqual = function(actual, expected) | assertEqual = function(actual, expected) | ||
if actual != expected then | if actual != expected then | ||
− | print "Unit test failure | + | print "Unit test failure: expected " + expected + ", got " + actual |
outer.errorCount = errorCount + 1 | outer.errorCount = errorCount + 1 | ||
end if | end if |
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