X-Git-Url: https://git.netwichtig.de/gitweb/?a=blobdiff_plain;f=data%2Frbot%2Fplugins%2Fmath.rb;h=a6baa7090bb014b737776abbbd85d49906fb41b0;hb=8b811d21babf8f9e5a10a953b595d55ebd08820d;hp=4a207389b02bc8dad44f6d8f22c42f732ba0a709;hpb=21949774b91eaec6ecde4eaa8ad121e2c0a36b87;p=user%2Fhenk%2Fcode%2Fruby%2Frbot.git diff --git a/data/rbot/plugins/math.rb b/data/rbot/plugins/math.rb index 4a207389..a6baa709 100644 --- a/data/rbot/plugins/math.rb +++ b/data/rbot/plugins/math.rb @@ -22,6 +22,9 @@ class MathPlugin < Plugin "ten" => "10" }; + def name + "math" + end def help(plugin, topic="") "math , evaluate mathematical expression" end @@ -36,12 +39,17 @@ class MathPlugin < Plugin expr.gsub!(/\b#{k}\b/, v) } + # ruby doesn't like floating-point values without a 0 + # in front of them, so find any non-digit followed by + # a . and insert a 0 before the . + expr.gsub!(/(\D|^)(\.\d+)/,'\10\2') + while expr =~ /(exp ([\w\d]+))/ exp = $1 val = Math.exp($2).to_s expr.gsub!(/#{Regexp.escape exp}/, "+#{val}") end - + while expr =~ /^\s*(dec2hex\s*(\d+))\s*\?*/ exp = $1 val = sprintf("%x", $2) @@ -53,13 +61,13 @@ class MathPlugin < Plugin while expr =~ /(log\s*((\d+\.?\d*)|\d*\.?\d+))\s*/ exp = $1 res = $2 - + if res == 0 val = "Infinity" else val = Math.log(res).to_s end - + expr.gsub!(/#{Regexp.escape exp}/, "+#{val}") end @@ -77,19 +85,20 @@ class MathPlugin < Plugin expr.gsub!(/\bover /, "/ ") expr.gsub!(/\bsquared/, "**2 ") expr.gsub!(/\bcubed/, "**3 ") - expr.gsub!(/\bto\s+(\d+)(r?st|nd|rd|th)?( power)?/, "**\1 ") + expr.gsub!(/\bto\s+(\d+)(r?st|nd|rd|th)?( power)?/, '**\1 ') expr.gsub!(/\bpercent of/, "*0.01*") expr.gsub!(/\bpercent/, "*0.01") expr.gsub!(/\% of\b/, "*0.01*") expr.gsub!(/\%/, "*0.01") - expr.gsub!(/\bsquare root of (\d+)/, "\1 ** 0.5 ") - expr.gsub!(/\bcubed? root of (\d+)/, "\1 **(1.0/3.0) ") + expr.gsub!(/\bsquare root of (\d+(\.\d+)?)/, '\1 ** 0.5 ') + expr.gsub!(/\bcubed? root of (\d+(\.\d+)?)/, '\1 **(1.0/3.0) ') expr.gsub!(/ of /, " * ") expr.gsub!(/(bit(-| )?)?xor(\'?e?d( with))?/, "^") expr.gsub!(/(bit(-| )?)?or(\'?e?d( with))?/, "|") expr.gsub!(/bit(-| )?and(\'?e?d( with))?/, "& ") expr.gsub!(/(plus|and)/, "+") + debug expr if (expr =~ /^\s*[-\d*+\s()\/^\.\|\&\*\!]+\s*$/ && expr !~ /^\s*\(?\d+\.?\d*\)?\s*$/ && expr !~ /^\s*$/ && @@ -106,9 +115,9 @@ class MathPlugin < Plugin answer = "a number with >30 digits..." end end - m.reply answer + m.reply answer.to_s rescue Exception => e - puts "couldn't evaluate expression \"#{m.params}\": #{e}" + error e m.reply "illegal expression \"#{m.params}\"" return end @@ -120,3 +129,4 @@ class MathPlugin < Plugin end plugin = MathPlugin.new plugin.register("math") +plugin.register("maths")