🕸📝Fergus Duniho wrote on Mon, Jan 9, 2023 07:11 PM UTC:
Defining Functions with Local Scope
I have sometimes conditionally defined functions within a subroutine for local use, but the def command normally defines functions at a global scope. So, if a subroutine defined a function, it could still be used when that subroutine was finished, and if it ran another subroutine (or itself recursively) that defined the same functions differently, this could mess things up. With this in mind, I realized it would be helpful to be able to define functions with a local scope.
Fortunately, I realized it was already possible, which saved me the trouble of adding this feature. To create a function with a local scope, save a lambda function to a variable with a local scope. You can then call it with the value of that variable. For example:
sub example kingpos:
local friend;
if hasupper space #kingpos:
set friend lambda (not haslower #0 and hasupper #0);
else:
set friend lambda (not hasupper #0 and haslower #0);
endif;
if fn #friend #piece:
...
endif;
endsub;
Defining Functions with Local Scope
I have sometimes conditionally defined functions within a subroutine for local use, but the
def
command normally defines functions at a global scope. So, if a subroutine defined a function, it could still be used when that subroutine was finished, and if it ran another subroutine (or itself recursively) that defined the same functions differently, this could mess things up. With this in mind, I realized it would be helpful to be able to define functions with a local scope.Fortunately, I realized it was already possible, which saved me the trouble of adding this feature. To create a function with a local scope, save a lambda function to a variable with a local scope. You can then call it with the value of that variable. For example: