IndexExpression.cs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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 IndexExpression : Expression, IVariable
  12. {
  13. Expression m_BaseExp;
  14. Expression m_IndexExp;
  15. public IndexExpression(IParseTree node, ScriptLoadingContext lcontext, Expression baseExp, Expression indexExp)
  16. :base(node, lcontext)
  17. {
  18. m_BaseExp = baseExp;
  19. m_IndexExp = indexExp;
  20. }
  21. public override RValue Eval(RuntimeScope scope)
  22. {
  23. RValue baseValue = m_BaseExp.Eval(scope).ToSimplestValue();
  24. RValue indexValue = m_IndexExp.Eval(scope).ToSimplestValue();
  25. if (baseValue.Type != DataType.Table)
  26. {
  27. throw new ScriptRuntimeException(this.TreeNode, "Can't index: {0}", baseValue.Type);
  28. }
  29. else
  30. {
  31. return baseValue.Table[indexValue];
  32. }
  33. }
  34. public void SetValue(RuntimeScope scope, RValue rValue)
  35. {
  36. RValue baseValue = m_BaseExp.Eval(scope).ToSimplestValue();
  37. RValue indexValue = m_IndexExp.Eval(scope).ToSimplestValue();
  38. baseValue.Table[indexValue] = rValue;
  39. }
  40. public override void Compile(Chunk bc)
  41. {
  42. m_BaseExp.Compile(bc);
  43. m_IndexExp.Compile(bc);
  44. bc.Index();
  45. }
  46. public void CompileAssignment(Chunk bc)
  47. {
  48. m_BaseExp.Compile(bc);
  49. m_IndexExp.Compile(bc);
  50. bc.IndexRef();
  51. }
  52. }
  53. }