mirror of
https://github.com/mruby/mruby
synced 2026-06-08 16:11:16 +00:00
7eaaee5405
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
```
28 lines
423 B
Ruby
28 lines
423 B
Ruby
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
|