From 7eaaee5405f71c598893e9a022c755f61f11e9ec Mon Sep 17 00:00:00 2001 From: "Yukihiro \"Matz\" Matsumoto" Date: Fri, 28 Aug 2020 17:49:27 +0900 Subject: 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 ``` --- mrbgems/mruby-catch/mrbgem.rake | 5 +++++ mrbgems/mruby-catch/mrblib/catch.rb | 27 +++++++++++++++++++++++++++ 2 files changed, 32 insertions(+) create mode 100644 mrbgems/mruby-catch/mrbgem.rake create mode 100644 mrbgems/mruby-catch/mrblib/catch.rb diff --git a/mrbgems/mruby-catch/mrbgem.rake b/mrbgems/mruby-catch/mrbgem.rake new file mode 100644 index 000000000..c714d443d --- /dev/null +++ b/mrbgems/mruby-catch/mrbgem.rake @@ -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 diff --git a/mrbgems/mruby-catch/mrblib/catch.rb b/mrbgems/mruby-catch/mrblib/catch.rb new file mode 100644 index 000000000..89eedf66a --- /dev/null +++ b/mrbgems/mruby-catch/mrblib/catch.rb @@ -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 -- cgit v1.2.3