Last active
August 21, 2022 18:14
-
-
Save eckardt/749074 to your computer and use it in GitHub Desktop.
implementation of squeak's non-local returns and translation example of squeak to javascript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// original code from http://michaelspeer.knome.net/2010/05/pattern-for-non-local-returns-in.html | |
var WithNonLocalReturn = function( block ){ | |
var nonLocalReturnException = function(){ | |
var value = null; | |
this.setReturnValue = function( retVal ){ value = retVal }; | |
this.getReturnValue = function( retVal ){ return value }; | |
} | |
var nonLocalReturnEx = new nonLocalReturnException(); | |
var insideStack = true; | |
var leave = function( retval ){ | |
if( insideStack ){ | |
nonLocalReturnEx.setReturnValue( retval ); | |
throw nonLocalReturnEx; | |
} else { | |
throw ( "" | |
+ "It is invalid to call the non-local return" | |
+ "outside the stack of the creating WithNonLocalReturn" | |
); | |
} | |
}; | |
try { | |
return block( leave ); | |
} catch ( e ) { | |
if( e instanceof nonLocalReturnException ){ | |
return e.getReturnValue(); | |
} else { | |
throw e; | |
} | |
} finally { | |
insideStack = false; | |
} | |
} | |
/* example Squeak and the corresponding JS code: | |
outerMethod | |
[ :arg | ^arg. JSGlobal alert: 'Will never be seen' ] value: 3. | |
^2. | |
*/ | |
block = function( f ) { | |
b = {}; | |
b.func = f; | |
b.value = function(args){ return this.func(args) }; | |
return b; | |
} | |
outerMethod = function(){ | |
return WithNonLocalReturn( function( nonLocalReturn ){ | |
block(function(arg){ | |
nonLocalReturn(arg); // This returns from outerMethod | |
alert("Will never be seen"); | |
}).value(3); | |
return(2); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment