mirror of
https://github.com/mruby/mruby
synced 2026-06-08 16:11:16 +00:00
Add a new gem: mruby-catch.
Implements `catch`/`throw` non-local jump inherited from Lisp.
`catch([tag]) {|tag| block } -> obj`
Example:
```
catch(:foo) { 123 } # => 123
catch(:foo) { throw(:foo, 456) } # => 456
catch(:foo) { throw(:foo) } # => nil
```
This commit is contained in:
@@ -0,0 +1,5 @@
|
||||
MRuby::Gem::Specification.new('mruby-catch') do |spec|
|
||||
spec.license = 'MIT'
|
||||
spec.author = 'mruby developers'
|
||||
spec.summary = 'Catch / Throw non-local Jump'
|
||||
end
|
||||
@@ -0,0 +1,27 @@
|
||||
class ThrowCatchJump < Exception
|
||||
def initialize(tag, val)
|
||||
@tag = tag
|
||||
@val = val
|
||||
super("uncaught throw :#{tag}")
|
||||
end
|
||||
def _tag
|
||||
@tag
|
||||
end
|
||||
def _val
|
||||
@val
|
||||
end
|
||||
end
|
||||
|
||||
module Kernel
|
||||
def catch(tag, &block)
|
||||
block.call(tag)
|
||||
rescue ThrowCatchJump => e
|
||||
unless e._tag == tag
|
||||
raise e
|
||||
end
|
||||
return e._val
|
||||
end
|
||||
def throw(tag, val=nil)
|
||||
raise ThrowCatchJump.new(tag, val)
|
||||
end
|
||||
end
|
||||
Reference in New Issue
Block a user