TableConstructor.cs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using MoonSharp.Interpreter.Execution;
  6. using MoonSharp.Interpreter.Grammar;
  7. namespace MoonSharp.Interpreter.Tree.Expressions
  8. {
  9. class TableConstructor : Expression
  10. {
  11. List<Expression> m_PositionalValues = new List<Expression>();
  12. List<KeyValuePair<Expression, Expression>> m_CtorArgs = new List<KeyValuePair<Expression, Expression>>();
  13. public TableConstructor(LuaParser.TableconstructorContext context, ScriptLoadingContext lcontext)
  14. : base(context, lcontext)
  15. {
  16. var fieldlist = context.fieldlist();
  17. if (fieldlist != null)
  18. {
  19. foreach (var field in fieldlist.field())
  20. {
  21. var keyval = field.keyexp;
  22. var name = field.NAME();
  23. if (keyval != null)
  24. {
  25. Expression exp = NodeFactory.CreateExpression(keyval, lcontext);
  26. m_CtorArgs.Add(new KeyValuePair<Expression,Expression>(
  27. exp,
  28. NodeFactory.CreateExpression(field.keyedexp, lcontext)));
  29. }
  30. else if (name != null)
  31. {
  32. m_CtorArgs.Add(new KeyValuePair<Expression, Expression>(
  33. new LiteralExpression(field, lcontext, new RValue(name.GetText())),
  34. NodeFactory.CreateExpression(field.namedexp, lcontext)));
  35. }
  36. else
  37. {
  38. m_PositionalValues.Add(NodeFactory.CreateExpression(field.positionalexp, lcontext));
  39. }
  40. }
  41. }
  42. }
  43. public override RValue Eval(RuntimeScope scope)
  44. {
  45. var dic = m_CtorArgs.ToDictionary(
  46. kvp => kvp.Key.Eval(scope),
  47. kvp => kvp.Value.Eval(scope).ToSimplestValue().CloneAsWritable());
  48. Table t = new Table(dic, m_PositionalValues.Select(e => e.Eval(scope)));
  49. return new RValue(t);
  50. }
  51. public override void Compile(Execution.VM.Chunk bc)
  52. {
  53. bc.NewTable();
  54. foreach (var kvp in m_CtorArgs)
  55. {
  56. kvp.Key.Compile(bc);
  57. bc.IndexSetN();
  58. kvp.Value.Compile(bc);
  59. bc.Store();
  60. }
  61. for (int i = 0; i < m_PositionalValues.Count; i++)
  62. {
  63. bc.Literal(new RValue(i+1));
  64. bc.IndexSetN();
  65. m_PositionalValues[i].Compile(bc);
  66. bc.Store();
  67. }
  68. }
  69. }
  70. }