Difference between revisions of "Expression eval"

From Kolmafia
Jump to navigation Jump to search
imported>Bale
(Start page. This needs a lot of work. r8824)
 
imported>Theraze
Line 19: Line 19:
 
code1={{CodeSample|
 
code1={{CodeSample|
 
title=Code Sample|
 
title=Code Sample|
description=This script expands modifier_eval() to include support for user-defined variables. It is extremely complex, but it is extremely useful to anyone who wants to use modifier_eval().|
+
description=This script expands expression_eval() to include support for user-defined variables. It is extremely complex, but it is extremely useful to anyone who wants to use expression_eval().|
 
code=
 
code=
 
<syntaxhighlight>
 
<syntaxhighlight>
Line 33: Line 33:
 
   }
 
   }
 
   m.append_tail(b);
 
   m.append_tail(b);
   return modifier_eval(b.to_string());
+
   return expression_eval(b.to_string());
 
}
 
}
  

Revision as of 14:39, 16 December 2010

Function Syntax

float expression_eval(string expression )

  • expression is a mathematical expression to be solved.

Evaluates an expression... somehow.

Code Sample

This script expands expression_eval() to include support for user-defined variables. It is extremely complex, but it is extremely useful to anyone who wants to use expression_eval().

float eval(string expr, float[string] vars) {
   buffer b;
   matcher m = create_matcher( "\\b[a-z_][a-zA-Z0-9_]*\\b", expr );
   while (m.find()) {
      string var = m.group(0);
      if (vars contains var) {
         m.append_replacement(b, vars[var].to_string());
      }
      // could implement functions, pref access, etc. here
   }
   m.append_tail(b);
   return expression_eval(b.to_string());
}

# Everything below this line shows how to make use of eval().
# TESTING:

float[string] v;
v["pi"] = 3.14159265;
v["ten"] = 10;
print(eval("2+3", v));
print(eval("max(pi^ten,ten^pi)", v));
print(eval("sqrt(pi)*L", v));
print(eval("undefined/2", v));