PowerOperatorExpression.cs 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using Antlr4.Runtime.Tree;
  6. using MoonSharp.Interpreter.Execution;
  7. using MoonSharp.Interpreter.Execution.VM;
  8. using MoonSharp.Interpreter.Grammar;
  9. namespace MoonSharp.Interpreter.Tree.Expressions
  10. {
  11. class PowerOperatorExpression : Expression
  12. {
  13. Expression m_Exp1, m_Exp2;
  14. public PowerOperatorExpression(IParseTree tree, ScriptLoadingContext lcontext)
  15. : base(tree, lcontext)
  16. {
  17. m_Exp1 = NodeFactory.CreateExpression(tree.GetChild(0), lcontext);
  18. m_Exp2 = NodeFactory.CreateExpression(tree.GetChild(2), lcontext);
  19. }
  20. public override void Compile(ByteCode bc)
  21. {
  22. m_Exp1.Compile(bc);
  23. m_Exp2.Compile(bc);
  24. bc.Emit_Operator(OpCode.Power);
  25. }
  26. public override DynValue Eval(ScriptExecutionContext context)
  27. {
  28. DynValue v1 = m_Exp1.Eval(context).ToScalar();
  29. DynValue v2 = m_Exp1.Eval(context).ToScalar();
  30. double? d1 = v1.CastToNumber();
  31. double? d2 = v1.CastToNumber();
  32. if (d1.HasValue && d2.HasValue)
  33. return DynValue.NewNumber(Math.Pow(d1.Value, d2.Value));
  34. throw new DynamicExpressionException("Attempt to perform arithmetic on non-numbers.");
  35. }
  36. }
  37. }