Browse Source

Refactoring of program structure!

Xanathar 11 years ago
parent
commit
0917355598
83 changed files with 1147 additions and 1181 deletions
  1. 26 24
      src/MoonSharp.Debugger/MainForm.cs
  2. 9 9
      src/MoonSharp.Debugger/ValueBrowser.cs
  3. 5 5
      src/MoonSharp.Interpreter.Tests/EndToEnd/ClosureTests.cs
  4. 11 9
      src/MoonSharp.Interpreter.Tests/EndToEnd/LuaTestSuiteExtract.cs
  5. 4 4
      src/MoonSharp.Interpreter.Tests/EndToEnd/MetatableTests.cs
  6. 47 47
      src/MoonSharp.Interpreter.Tests/EndToEnd/SimpleTests.cs
  7. 12 12
      src/MoonSharp.Interpreter.Tests/EndToEnd/TableTests.cs
  8. 7 7
      src/MoonSharp.Interpreter.Tests/EndToEnd/TailCallTests.cs
  9. 9 6
      src/MoonSharp.Interpreter.Tests/TestMore/TapRunner.cs
  10. 1 1
      src/MoonSharp.Interpreter.Tests/TestMore/TestMoreTests.cs
  11. 52 29
      src/MoonSharp.Interpreter/CoreLib/BasicMethods.cs
  12. 0 35
      src/MoonSharp.Interpreter/CoreLib/CoreLibModule.cs
  13. 11 0
      src/MoonSharp.Interpreter/CoreLib/ErrorHandling.cs
  14. 61 0
      src/MoonSharp.Interpreter/CoreLib/LoadMethods.cs
  15. 21 21
      src/MoonSharp.Interpreter/CoreLib/MetaTableMethods.cs
  16. 18 18
      src/MoonSharp.Interpreter/CoreLib/TableIterators.cs
  17. 1 1
      src/MoonSharp.Interpreter/Debugging/IDebugger.cs
  18. 2 2
      src/MoonSharp.Interpreter/Debugging/WatchItem.cs
  19. 7 7
      src/MoonSharp.Interpreter/Execution/DataTypes/CallbackArguments.cs
  20. 3 3
      src/MoonSharp.Interpreter/Execution/DataTypes/CallbackFunction.cs
  21. 3 1
      src/MoonSharp.Interpreter/Execution/DataTypes/Closure.cs
  22. 0 73
      src/MoonSharp.Interpreter/Execution/DataTypes/LRef.cs
  23. 0 450
      src/MoonSharp.Interpreter/Execution/DataTypes/RValue.cs
  24. 73 0
      src/MoonSharp.Interpreter/Execution/DataTypes/SymbolRef.cs
  25. 1 1
      src/MoonSharp.Interpreter/Execution/DataTypes/SymbolRefType.cs
  26. 11 11
      src/MoonSharp.Interpreter/Execution/DataTypes/Table.cs
  27. 5 5
      src/MoonSharp.Interpreter/Execution/DataTypes/TablePair.cs
  28. 26 0
      src/MoonSharp.Interpreter/Execution/FileLoadRequestedEventArgs.cs
  29. 18 0
      src/MoonSharp.Interpreter/Execution/IExecutionContext.cs
  30. 6 6
      src/MoonSharp.Interpreter/Execution/Scopes/BuildTimeScope.cs
  31. 5 5
      src/MoonSharp.Interpreter/Execution/Scopes/BuildTimeScopeBlock.cs
  32. 5 5
      src/MoonSharp.Interpreter/Execution/Scopes/BuildTimeScopeFrame.cs
  33. 2 2
      src/MoonSharp.Interpreter/Execution/Scopes/ClosureContext.cs
  34. 1 1
      src/MoonSharp.Interpreter/Execution/Scopes/IClosureBuilder.cs
  35. 1 1
      src/MoonSharp.Interpreter/Execution/Scopes/LoopTracker.cs
  36. 2 2
      src/MoonSharp.Interpreter/Execution/Scopes/RuntimeScopeFrame.cs
  37. 183 28
      src/MoonSharp.Interpreter/Execution/Script.cs
  38. 12 7
      src/MoonSharp.Interpreter/Execution/VM/ByteCode.cs
  39. 2 2
      src/MoonSharp.Interpreter/Execution/VM/CallStackItem.cs
  40. 4 4
      src/MoonSharp.Interpreter/Execution/VM/Instruction.cs
  41. 1 0
      src/MoonSharp.Interpreter/Execution/VM/OpCode.cs
  42. 20 17
      src/MoonSharp.Interpreter/Execution/VM/Processor/Processor.cs
  43. 4 4
      src/MoonSharp.Interpreter/Execution/VM/Processor/Processor_Debugger.cs
  44. 13 7
      src/MoonSharp.Interpreter/Execution/VM/Processor/Processor_IExecutionContext.cs
  45. 117 141
      src/MoonSharp.Interpreter/Execution/VM/Processor/Processor_InstructionLoop.cs
  46. 25 22
      src/MoonSharp.Interpreter/Execution/VM/Processor/Processor_Scope.cs
  47. 51 11
      src/MoonSharp.Interpreter/Execution/VM/Processor/Processor_UtilityFunctions.cs
  48. 30 0
      src/MoonSharp.Interpreter/Modules/CoreModules.cs
  49. 32 7
      src/MoonSharp.Interpreter/Modules/ModuleRegister.cs
  50. 17 8
      src/MoonSharp.Interpreter/MoonSharp.Interpreter.csproj
  51. 1 36
      src/MoonSharp.Interpreter/MoonSharpInterpreter.cs
  52. 29 0
      src/MoonSharp.Interpreter/Tree/Expressions/AdjustmentExpression.cs
  53. 1 1
      src/MoonSharp.Interpreter/Tree/Expressions/ExprListExpression.cs
  54. 1 1
      src/MoonSharp.Interpreter/Tree/Expressions/FunctionCallChainExpression.cs
  55. 9 9
      src/MoonSharp.Interpreter/Tree/Expressions/FunctionDefinitionExpression.cs
  56. 2 2
      src/MoonSharp.Interpreter/Tree/Expressions/IndexExpression.cs
  57. 7 7
      src/MoonSharp.Interpreter/Tree/Expressions/LiteralExpression.cs
  58. 1 1
      src/MoonSharp.Interpreter/Tree/Expressions/OperatorExpression.cs
  59. 3 3
      src/MoonSharp.Interpreter/Tree/Expressions/SymbolRefExpression.cs
  60. 3 3
      src/MoonSharp.Interpreter/Tree/Expressions/TableConstructor.cs
  61. 2 2
      src/MoonSharp.Interpreter/Tree/FunctionCall.cs
  62. 1 1
      src/MoonSharp.Interpreter/Tree/IVariable.cs
  63. 1 1
      src/MoonSharp.Interpreter/Tree/Loop.cs
  64. 1 1
      src/MoonSharp.Interpreter/Tree/NodeBase.cs
  65. 18 4
      src/MoonSharp.Interpreter/Tree/NodeFactory.cs
  66. 1 1
      src/MoonSharp.Interpreter/Tree/Statements/AssignmentStatement.cs
  67. 1 1
      src/MoonSharp.Interpreter/Tree/Statements/BreakStatement.cs
  68. 44 2
      src/MoonSharp.Interpreter/Tree/Statements/ChunkStatement.cs
  69. 1 1
      src/MoonSharp.Interpreter/Tree/Statements/CompositeStatement.cs
  70. 3 3
      src/MoonSharp.Interpreter/Tree/Statements/ForEachLoopStatement.cs
  71. 3 3
      src/MoonSharp.Interpreter/Tree/Statements/ForLoopStatement.cs
  72. 1 1
      src/MoonSharp.Interpreter/Tree/Statements/FunctionCallStatement.cs
  73. 6 6
      src/MoonSharp.Interpreter/Tree/Statements/FunctionDefinitionStatement.cs
  74. 1 1
      src/MoonSharp.Interpreter/Tree/Statements/IfStatement.cs
  75. 1 1
      src/MoonSharp.Interpreter/Tree/Statements/LabelStatement.cs
  76. 2 2
      src/MoonSharp.Interpreter/Tree/Statements/LocalAssignmentStatement.cs
  77. 1 1
      src/MoonSharp.Interpreter/Tree/Statements/NullStatement.cs
  78. 1 1
      src/MoonSharp.Interpreter/Tree/Statements/RepeatStatement.cs
  79. 1 1
      src/MoonSharp.Interpreter/Tree/Statements/ReturnStatement.cs
  80. 1 1
      src/MoonSharp.Interpreter/Tree/Statements/ScopeBlockStatement.cs
  81. 1 1
      src/MoonSharp.Interpreter/Tree/Statements/WhileStatement.cs
  82. 9 10
      src/MoonSharp/Program.cs
  83. 12 11
      src/PerformanceComparison/Program.cs

+ 26 - 24
src/MoonSharp.Debugger/MainForm.cs

@@ -48,27 +48,27 @@ namespace MoonSharp.Debugger
 		Script m_Script;
 		SynchronizationContext m_Ctx;
 
-		RValue Print(IExecutionContext executionContext, CallbackArguments values)
+		DynValue Print(IExecutionContext executionContext, CallbackArguments values)
 		{
-			string prn = string.Join(" ", values.List.Select(v => v.AsString()).ToArray());
+			string prn = string.Join(" ", values.List.Select(v => v.ToPrintString()).ToArray());
 			Console_WriteLine("{0}", prn);
-			return RValue.Nil;
+			return DynValue.Nil;
 		}
 
-		RValue Assert(IExecutionContext executionContext, CallbackArguments values)
+		DynValue Assert(IExecutionContext executionContext, CallbackArguments values)
 		{
-			if (!values[0].TestAsBoolean())
+			if (!values[0].CastToBool())
 				Console_WriteLine("ASSERT FAILED!");
 
-			return RValue.Nil;
+			return DynValue.Nil;
 		}
 
-		RValue XAssert(IExecutionContext executionContext, CallbackArguments values)
+		DynValue XAssert(IExecutionContext executionContext, CallbackArguments values)
 		{
-			if (!values[1].TestAsBoolean())
+			if (!values[1].CastToBool())
 				Console_WriteLine("ASSERT FAILED! : {0}", values[0].ToString());
 
-			return RValue.Nil;
+			return DynValue.Nil;
 		}
 
 		private void Console_WriteLine(string fmt, params object[] args)
@@ -87,17 +87,24 @@ namespace MoonSharp.Debugger
 
 		private void DebugScript(string filename)
 		{
-			m_Script = MoonSharpInterpreter.LoadFromFile(filename);
+			Table T = new Table();
+			T["print"] = DynValue.NewCallback(Print);
+			T["assert"] = DynValue.NewCallback(Assert);
+			T["xassert"] = DynValue.NewCallback(XAssert);
+
+			m_Script = new Script(T);
+
+			m_Script.LoadFile(filename);
+
 			m_Script.AttachDebugger(this);
 
 			Thread m_Debugger = new Thread(DebugMain);
 			m_Debugger.Name = "Moon# Execution Thread";
 			m_Debugger.IsBackground = true;
 			m_Debugger.Start();
-
 		}
 
-		void IDebugger.SetSourceCode(Chunk byteCode, string[] code)
+		void IDebugger.SetSourceCode(ByteCode byteCode, string[] code)
 		{
 			string[] source = new string[byteCode.Code.Count];
 
@@ -142,14 +149,9 @@ namespace MoonSharp.Debugger
 
 		void DebugMain()
 		{
-			Table T = new Table();
-			T["print"] = new RValue(new CallbackFunction(Print));
-			T["assert"] = new RValue(new CallbackFunction(Assert));
-			T["xassert"] = new RValue(new CallbackFunction(XAssert));
-
 			try
 			{
-				m_Script.Execute(T);
+				m_Script.Call(0, m_Script.GetMainChunk());
 			}
 			catch (Exception ex)
 			{
@@ -309,28 +311,28 @@ namespace MoonSharp.Debugger
 
 		private void btnViewVStk_Click(object sender, EventArgs e)
 		{
-			ValueBrowser.StartBrowse(lvVStack.SelectedItems.OfType<ListViewItem>().Select(lvi => lvi.Tag).Cast<RValue>().FirstOrDefault());
+			ValueBrowser.StartBrowse(lvVStack.SelectedItems.OfType<ListViewItem>().Select(lvi => lvi.Tag).Cast<DynValue>().FirstOrDefault());
 		}
 
 		private void lvVStack_MouseDoubleClick(object sender, MouseEventArgs e)
 		{
-			ValueBrowser.StartBrowse(lvVStack.SelectedItems.OfType<ListViewItem>().Select(lvi => lvi.Tag).Cast<RValue>().FirstOrDefault());
+			ValueBrowser.StartBrowse(lvVStack.SelectedItems.OfType<ListViewItem>().Select(lvi => lvi.Tag).Cast<DynValue>().FirstOrDefault());
 		}
 
 		private void btnViewWatch_Click(object sender, EventArgs e)
 		{
-			ValueBrowser.StartBrowse(lvWatches.SelectedItems.OfType<ListViewItem>().Select(lvi => lvi.Tag).Cast<RValue>().FirstOrDefault());
+			ValueBrowser.StartBrowse(lvWatches.SelectedItems.OfType<ListViewItem>().Select(lvi => lvi.Tag).Cast<DynValue>().FirstOrDefault());
 		}
 
 
 		private void lvWatches_MouseDoubleClick(object sender, MouseEventArgs e)
 		{
-			ValueBrowser.StartBrowse(lvWatches.SelectedItems.OfType<ListViewItem>().Select(lvi => lvi.Tag).Cast<RValue>().FirstOrDefault());
+			ValueBrowser.StartBrowse(lvWatches.SelectedItems.OfType<ListViewItem>().Select(lvi => lvi.Tag).Cast<DynValue>().FirstOrDefault());
 		}
 
 		private void toolGoToCodeVStack_Click(object sender, EventArgs e)
 		{
-			var v = lvVStack.SelectedItems.OfType<ListViewItem>().Select(lvi => lvi.Tag).Cast<RValue>().FirstOrDefault();
+			var v = lvVStack.SelectedItems.OfType<ListViewItem>().Select(lvi => lvi.Tag).Cast<DynValue>().FirstOrDefault();
 
 			if (v != null && v.Type == DataType.Function)
 				GotoBytecode(v.Function.ByteCodeLocation);
@@ -338,7 +340,7 @@ namespace MoonSharp.Debugger
 
 		private void toolGoToCodeWatches_Click(object sender, EventArgs e)
 		{
-			var v = lvWatches.SelectedItems.OfType<ListViewItem>().Select(lvi => lvi.Tag).Cast<RValue>().FirstOrDefault();
+			var v = lvWatches.SelectedItems.OfType<ListViewItem>().Select(lvi => lvi.Tag).Cast<DynValue>().FirstOrDefault();
 
 			if (v != null && v.Type == DataType.Function)
 				GotoBytecode(v.Function.ByteCodeLocation);

+ 9 - 9
src/MoonSharp.Debugger/ValueBrowser.cs

@@ -12,8 +12,8 @@ namespace MoonSharp.Debugger
 {
 	public partial class ValueBrowser : Form
 	{
-		Stack<RValue> m_ValueStack = new Stack<RValue>();
-		public static void StartBrowse(RValue v)
+		Stack<DynValue> m_ValueStack = new Stack<DynValue>();
+		public static void StartBrowse(DynValue v)
 		{
 			if (v == null)
 				return;
@@ -35,7 +35,7 @@ namespace MoonSharp.Debugger
 
 		private void InvalidateData()
 		{
-			RValue V = m_ValueStack.Peek();
+			DynValue V = m_ValueStack.Peek();
 			toolBack.Enabled = (m_ValueStack.Count > 1);
 
 			lvMetaTable.BeginUpdate();
@@ -124,14 +124,14 @@ namespace MoonSharp.Debugger
 		{
 			foreach (ListViewItem lvi in lv.Items)
 			{
-				if (lvi.Tag is RValue)
+				if (lvi.Tag is DynValue)
 				{
 					lvi.ForeColor = Color.Blue;
 				}
 			}
 		}
 
-		private void BuildSymbolTable(RValue V)
+		private void BuildSymbolTable(DynValue V)
 		{
 			var S = V.Symbol;
 			lvTableData.Add("Type", S.Type);
@@ -141,7 +141,7 @@ namespace MoonSharp.Debugger
 			lvTableData.Add("Table Ref Object", S.TableRefObject).Tag = S.TableRefObject;
 		}
 
-		private void BuildFunctionTable(RValue V)
+		private void BuildFunctionTable(DynValue V)
 		{
 			var F = V.Function;
 			var C = F.ClosureContext;
@@ -153,7 +153,7 @@ namespace MoonSharp.Debugger
 			}
 		}
 
-		private void BuildTupleTable(RValue V)
+		private void BuildTupleTable(DynValue V)
 		{
 			var T = V.Tuple;
 
@@ -163,7 +163,7 @@ namespace MoonSharp.Debugger
 			}
 		}
 
-		private void BuildTableTable(ListView listView, RValue V)
+		private void BuildTableTable(ListView listView, DynValue V)
 		{
 			var T = V.Table;
 
@@ -207,7 +207,7 @@ namespace MoonSharp.Debugger
 			ListViewItem lvi = listView.SelectedItems.OfType<ListViewItem>().FirstOrDefault();
 			if (lvi == null) return;
 
-			RValue v = lvi.Tag as RValue;
+			DynValue v = lvi.Tag as DynValue;
 
 			if (v != null)
 			{

+ 5 - 5
src/MoonSharp.Interpreter.Tests/EndToEnd/ClosureTests.cs

@@ -20,7 +20,7 @@ namespace MoonSharp.Interpreter.Tests
 
 				return (g(3)(2));";
 
-			RValue res = MoonSharpInterpreter.LoadFromString(script).Execute(null);
+			DynValue res = Script.RunString(script);
 
 			Assert.AreEqual(DataType.Number, res.Type);
 			Assert.AreEqual(5, res.Number);
@@ -52,7 +52,7 @@ namespace MoonSharp.Interpreter.Tests
 						return a[1](), a[2](), a[3](), a[4](), a[5]()";
 
 
-			RValue res = MoonSharpInterpreter.LoadFromString(script).Execute(null);
+			DynValue res = Script.RunString(script);
 
 			Assert.AreEqual(DataType.Tuple, res.Type);
 			Assert.AreEqual(5, res.Tuple.Length);
@@ -92,7 +92,7 @@ namespace MoonSharp.Interpreter.Tests
 
 						return a[1](), a[2](), a[3](), a[4](), a[5]()";
 
-			RValue res = MoonSharpInterpreter.LoadFromString(script).Execute(null);
+			DynValue res = Script.RunString(script);
 
 			Assert.AreEqual(DataType.Tuple, res.Type);
 			Assert.AreEqual(5, res.Tuple.Length);
@@ -133,7 +133,7 @@ namespace MoonSharp.Interpreter.Tests
 
 						return a[1](), a[2](), a[3](), a[4](), a[5]()";
 
-			RValue res = MoonSharpInterpreter.LoadFromString(script).Execute(null);
+			DynValue res = Script.RunString(script);
 
 			Assert.AreEqual(DataType.Tuple, res.Type);
 			Assert.AreEqual(5, res.Tuple.Length);
@@ -177,7 +177,7 @@ namespace MoonSharp.Interpreter.Tests
 
 				return a1(), a2(), a3(), a4(), a5()";
 
-			RValue res = MoonSharpInterpreter.LoadFromString(script).Execute(null);
+			DynValue res = Script.RunString(script);
 
 			Assert.AreEqual(DataType.Tuple, res.Type);
 			Assert.AreEqual(5, res.Tuple.Length);

+ 11 - 9
src/MoonSharp.Interpreter.Tests/EndToEnd/LuaTestSuiteExtract.cs

@@ -20,32 +20,34 @@ namespace MoonSharp.Interpreter.Tests
 			int i = 0;
 
 			var globalCtx = new Table();
-			globalCtx[new RValue("xassert")] = new RValue(new CallbackFunction(
+			globalCtx[DynValue.NewString("xassert")] =  DynValue.NewCallback(new CallbackFunction(
 				(x, a) =>
 				{
-					if (!a[1].TestAsBoolean())
+					if (!a[1].CastToBool())
 						failedTests.Add(a[0].String);
 
-					return RValue.Nil;
+					return DynValue.Nil;
 				}));
-			globalCtx[new RValue("assert")] = new RValue(new CallbackFunction(
+			globalCtx[DynValue.NewString("assert")] =  DynValue.NewCallback(new CallbackFunction(
 			 (x, a) =>
 			 {
 				 ++i;
 
-				 if (!a[0].TestAsBoolean())
+				 if (!a[0].CastToBool())
 					 failedTests.Add(string.Format("assert #{0}", i));
 
-				 return RValue.Nil;
+				 return DynValue.Nil;
 			 }));
 
-			globalCtx[new RValue("print")] = new RValue(new CallbackFunction((x, a) =>
+			globalCtx[DynValue.NewString("print")] =  DynValue.NewCallback(new CallbackFunction((x, a) =>
 				{
 					// Debug.WriteLine(string.Join(" ", a.Select(v => v.AsString()).ToArray()));
-					return RValue.Nil;
+					return DynValue.Nil;
 				}));
 
-			RValue res = MoonSharpInterpreter.LoadFromString(script).Execute(globalCtx);
+			Script S = new Script(globalCtx);
+
+			DynValue res = S.DoString(script);
 
 			Assert.IsFalse(failedTests.Any(), string.Format("Failed asserts {0}",
 				string.Join(", ", failedTests.Select(xi => xi.ToString()).ToArray())));

+ 4 - 4
src/MoonSharp.Interpreter.Tests/EndToEnd/MetatableTests.cs

@@ -45,7 +45,7 @@ namespace MoonSharp.Interpreter.Tests.EndToEnd
 			globalCtx.RegisterModuleType<TableIterators>();
 			globalCtx.RegisterModuleType<MetaTableMethods>();
 
-			RValue res = MoonSharpInterpreter.LoadFromString(script).Execute(globalCtx);
+			DynValue res = (new Script(globalCtx)).DoString(script);
 
 			Assert.AreEqual(DataType.String, res.Type);
 			Assert.AreEqual("321", res.String);
@@ -78,7 +78,7 @@ namespace MoonSharp.Interpreter.Tests.EndToEnd
 			globalCtx.RegisterModuleType<TableIterators>();
 			globalCtx.RegisterModuleType<MetaTableMethods>();
 
-			RValue res = MoonSharpInterpreter.LoadFromString(script).Execute(globalCtx);
+			DynValue res = (new Script(globalCtx)).DoString(script);
 
 			Assert.AreEqual(DataType.Number, res.Type);
 			Assert.AreEqual(24, res.Number);
@@ -106,7 +106,7 @@ namespace MoonSharp.Interpreter.Tests.EndToEnd
 			globalCtx.RegisterModuleType<TableIterators>();
 			globalCtx.RegisterModuleType<MetaTableMethods>();
 
-			RValue res = MoonSharpInterpreter.LoadFromString(script).Execute(globalCtx);
+			DynValue res = (new Script(globalCtx)).DoString(script);
 
 			Assert.AreEqual(DataType.Tuple, res.Type);
 			Assert.AreEqual(true, res.Tuple[0].Boolean);
@@ -139,7 +139,7 @@ namespace MoonSharp.Interpreter.Tests.EndToEnd
 			globalCtx.RegisterModuleType<TableIterators>();
 			globalCtx.RegisterModuleType<MetaTableMethods>();
 
-			RValue res = MoonSharpInterpreter.LoadFromString(script).Execute(globalCtx);
+			DynValue res = (new Script(globalCtx)).DoString(script);
 
 
 			Assert.AreEqual(DataType.Number, res.Type);

+ 47 - 47
src/MoonSharp.Interpreter.Tests/EndToEnd/SimpleTests.cs

@@ -13,18 +13,18 @@ namespace MoonSharp.Interpreter.Tests
 		[Test]
 		public void CSharpStaticFunctionCallStatement()
 		{
-			IList<RValue> args = null;
+			IList<DynValue> args = null;
 
 			string script = "print(\"hello\", \"world\");";
 
 			var globalCtx = new Table();
-			globalCtx[new RValue("print")] = new RValue(new CallbackFunction((x, a) => 
+			globalCtx["print"] = DynValue.NewCallback(new CallbackFunction((x, a) => 
 			{
-				args = a.ToArray(); 
-				return new RValue(1234.0); 
+				args = a.ToArray();
+				return DynValue.NewNumber(1234.0); 
 			}));
 
-			RValue res = MoonSharpInterpreter.LoadFromString(script).Execute(globalCtx);
+			DynValue res = (new Script(globalCtx)).DoString(script);
 
 			Assert.AreEqual(DataType.Nil, res.Type);
 			Assert.AreEqual(2, args.Count);
@@ -37,14 +37,14 @@ namespace MoonSharp.Interpreter.Tests
 		[Test]
 		public void CSharpStaticFunctionCallRedef()
 		{
-			IList<RValue> args = null;
+			IList<DynValue> args = null;
 
 			string script = "local print = print; print(\"hello\", \"world\");";
 
 			var globalCtx = new Table();
-			globalCtx[new RValue("print")] = new RValue(new CallbackFunction((_x, a) => { args = a.ToArray(); return new RValue(1234.0); }));
+			globalCtx["print"] = DynValue.NewCallback(new CallbackFunction((_x, a) => { args = a.ToArray(); return DynValue.NewNumber(1234.0); }));
 
-			RValue res = MoonSharpInterpreter.LoadFromString(script).Execute(globalCtx);
+			DynValue res = (new Script(globalCtx)).DoString(script);
 
 			Assert.AreEqual(2, args.Count);
 			Assert.AreEqual(DataType.String, args[0].Type);
@@ -57,14 +57,14 @@ namespace MoonSharp.Interpreter.Tests
 		[Test]
 		public void CSharpStaticFunctionCall()
 		{
-			IList<RValue> args = null;
+			IList<DynValue> args = null;
 
 			string script = "return print(\"hello\", \"world\");";
 
 			var globalCtx = new Table();
-			globalCtx[new RValue("print")] = new RValue(new CallbackFunction((_x, a) => { args = a.ToArray(); return new RValue(1234.0); }));
+			globalCtx["print"] = DynValue.NewCallback(new CallbackFunction((_x, a) => { args = a.ToArray(); return DynValue.NewNumber(1234.0); }));
 
-			RValue res = MoonSharpInterpreter.LoadFromString(script).Execute(globalCtx);
+			DynValue res = (new Script(globalCtx)).DoString(script);
 
 			Assert.AreEqual(2, args.Count);
 			Assert.AreEqual(DataType.String, args[0].Type);
@@ -89,7 +89,7 @@ namespace MoonSharp.Interpreter.Tests
 
 				return x,y,z";
 
-			RValue res = MoonSharpInterpreter.LoadFromString(script).Execute(null);
+			DynValue res = Script.RunString(script);
 
 			Assert.AreEqual(3, res.Tuple.Length);
 			Assert.AreEqual(DataType.String, res.Tuple[0].Type);
@@ -105,7 +105,7 @@ namespace MoonSharp.Interpreter.Tests
 		{
 			string script = @"return 6*7";
 
-			RValue res = MoonSharpInterpreter.LoadFromString(script).Execute(null);
+			DynValue res = Script.RunString(script);
 
 			Assert.AreEqual(DataType.Number, res.Type);
 			Assert.AreEqual(42, res.Number);
@@ -121,12 +121,12 @@ namespace MoonSharp.Interpreter.Tests
 			";
 
 			var globalCtx = new Table();
-			globalCtx[new RValue("crash")] = new RValue(new CallbackFunction((_x, a) =>
+			globalCtx["crash"] = DynValue.NewCallback(new CallbackFunction((_x, a) =>
 			{
 				throw new Exception("FAIL!");
 			}));
 
-			MoonSharpInterpreter.LoadFromString(script).Execute(globalCtx);
+			(new Script(globalCtx)).DoString(script);
 		}
 
 
@@ -146,7 +146,7 @@ namespace MoonSharp.Interpreter.Tests
 
 				return false or f(), true or f(), false and f(), true and f(), i";
 
-			RValue res = MoonSharpInterpreter.LoadFromString(script).Execute(null);
+			DynValue res = Script.RunString(script);
 
 			Assert.AreEqual(5, res.Tuple.Length);
 			Assert.AreEqual(DataType.String, res.Tuple[0].Type);
@@ -174,7 +174,7 @@ namespace MoonSharp.Interpreter.Tests
 			move(4, 1, 2, 3)
 			";
 
-			RValue res = MoonSharpInterpreter.LoadFromString(script).Execute(null);
+			DynValue res = Script.RunString(script);
 		}
 
 		[Test]
@@ -192,7 +192,7 @@ namespace MoonSharp.Interpreter.Tests
     
 				return fact(5)";
 
-			RValue res = MoonSharpInterpreter.LoadFromString(script).Execute(null);
+			DynValue res = Script.RunString(script);
 
 			Assert.AreEqual(DataType.Number, res.Type);
 			Assert.AreEqual(120.0, res.Number);
@@ -211,7 +211,7 @@ namespace MoonSharp.Interpreter.Tests
     
 				return i, x";
 
-			RValue res = MoonSharpInterpreter.LoadFromString(script).Execute(null);
+			DynValue res = Script.RunString(script);
 
 			Assert.AreEqual(DataType.Tuple, res.Type);
 			Assert.AreEqual(2, res.Tuple.Length);
@@ -232,7 +232,7 @@ namespace MoonSharp.Interpreter.Tests
 		
 				return i, x";
 
-			RValue res = MoonSharpInterpreter.LoadFromString(script).Execute(null);
+			DynValue res = Script.RunString(script);
 
 			Assert.AreEqual(DataType.Tuple, res.Type);
 			Assert.AreEqual(2, res.Tuple.Length);
@@ -254,7 +254,7 @@ namespace MoonSharp.Interpreter.Tests
     
 				return x";
 
-			RValue res = MoonSharpInterpreter.LoadFromString(script).Execute(null);
+			DynValue res = Script.RunString(script);
 
 			Assert.AreEqual(DataType.Number, res.Type);
 			Assert.AreEqual(1, res.Number);
@@ -293,7 +293,7 @@ namespace MoonSharp.Interpreter.Tests
     
 				return x, y";
 
-			RValue res = MoonSharpInterpreter.LoadFromString(script).Execute(null);
+			DynValue res = Script.RunString(script);
 
 			Assert.AreEqual(DataType.Tuple, res.Type);
 			Assert.AreEqual(2, res.Tuple.Length);
@@ -332,7 +332,7 @@ namespace MoonSharp.Interpreter.Tests
     
 				return x, y";
 
-			RValue res = MoonSharpInterpreter.LoadFromString(script).Execute(null);
+			DynValue res = Script.RunString(script);
 
 			Assert.AreEqual(DataType.Tuple, res.Type);
 			Assert.AreEqual(2, res.Tuple.Length);
@@ -351,7 +351,7 @@ namespace MoonSharp.Interpreter.Tests
    
 				return #x, #y";
 
-			RValue res = MoonSharpInterpreter.LoadFromString(script).Execute(null);
+			DynValue res = Script.RunString(script);
 
 			Assert.AreEqual(DataType.Tuple, res.Type);
 			Assert.AreEqual(2, res.Tuple.Length);
@@ -378,7 +378,7 @@ namespace MoonSharp.Interpreter.Tests
     
 				return i, x";
 
-			RValue res = MoonSharpInterpreter.LoadFromString(script).Execute(null);
+			DynValue res = Script.RunString(script);
 
 			Assert.AreEqual(DataType.Tuple, res.Type);
 			Assert.AreEqual(2, res.Tuple.Length);
@@ -401,7 +401,7 @@ namespace MoonSharp.Interpreter.Tests
     
 				return fact(5)";
 
-			RValue res = MoonSharpInterpreter.LoadFromString(script).Execute(null);
+			DynValue res = Script.RunString(script);
 
 			Assert.AreEqual(DataType.Number, res.Type);
 			Assert.AreEqual(120.0, res.Number);
@@ -412,7 +412,7 @@ namespace MoonSharp.Interpreter.Tests
 		{
 			string script = @"return 5+3*7-2*5+2^3^2";
 
-			RValue res = MoonSharpInterpreter.LoadFromString(script).Execute(null);
+			DynValue res = Script.RunString(script);
 
 			Assert.AreEqual(DataType.Number, res.Type);
 			Assert.AreEqual(528, res.Number);
@@ -423,7 +423,7 @@ namespace MoonSharp.Interpreter.Tests
 		{
 			string script = @"return (5+3)*7-2*5+(2^3)^2";
 
-			RValue res = MoonSharpInterpreter.LoadFromString(script).Execute(null);
+			DynValue res = Script.RunString(script);
 
 			Assert.AreEqual(DataType.Number, res.Type);
 			Assert.AreEqual(110, res.Number);
@@ -434,7 +434,7 @@ namespace MoonSharp.Interpreter.Tests
 		{
 			string script = @"x = 1; return x;";    
 
-			RValue res = MoonSharpInterpreter.LoadFromString(script).Execute(null);
+			DynValue res = Script.RunString(script);
 
 			Assert.AreEqual(DataType.Number, res.Type);
 			Assert.AreEqual(1, res.Number);
@@ -455,7 +455,7 @@ namespace MoonSharp.Interpreter.Tests
     
 				return w+x+y+z";
 
-			RValue res = MoonSharpInterpreter.LoadFromString(script).Execute(null);
+			DynValue res = Script.RunString(script);
 
 			Assert.AreEqual(DataType.Number, res.Type);
 			Assert.AreEqual(6, res.Number);
@@ -476,7 +476,7 @@ namespace MoonSharp.Interpreter.Tests
     
 				return fact(5)";
 
-			RValue res = MoonSharpInterpreter.LoadFromString(script).Execute(null);
+			DynValue res = Script.RunString(script);
 
 			Assert.AreEqual(DataType.Number, res.Type);
 			Assert.AreEqual(120.0, res.Number);
@@ -500,7 +500,7 @@ namespace MoonSharp.Interpreter.Tests
     
 				return fact(5)";
 
-			RValue res = MoonSharpInterpreter.LoadFromString(script).Execute(null);
+			DynValue res = Script.RunString(script);
 
 			Assert.AreEqual(DataType.Number, res.Type);
 			Assert.AreEqual(120.0, res.Number);
@@ -519,7 +519,7 @@ namespace MoonSharp.Interpreter.Tests
 					return x;
 			";
 
-			RValue res = MoonSharpInterpreter.LoadFromString(script).Execute(null);
+			DynValue res = Script.RunString(script);
 
 			Assert.AreEqual(DataType.Number, res.Type);
 			Assert.AreEqual(6.0, res.Number);
@@ -535,7 +535,7 @@ namespace MoonSharp.Interpreter.Tests
     
 				return fact(3)";
 
-			RValue res = MoonSharpInterpreter.LoadFromString(script).Execute(null);
+			DynValue res = Script.RunString(script);
 
 			Assert.AreEqual(DataType.Number, res.Type);
 			Assert.AreEqual(3, res.Number);
@@ -557,7 +557,7 @@ namespace MoonSharp.Interpreter.Tests
     
 				return fact(5)";
 
-			RValue res = MoonSharpInterpreter.LoadFromString(script).Execute(null);
+			DynValue res = Script.RunString(script);
 
 			Assert.AreEqual(DataType.Number, res.Type);
 			Assert.AreEqual(120.0, res.Number);
@@ -575,7 +575,7 @@ namespace MoonSharp.Interpreter.Tests
 				return fact();
 				";
 
-			RValue res = MoonSharpInterpreter.LoadFromString(script).Execute(null);
+			DynValue res = Script.RunString(script);
 
 			Assert.AreEqual(DataType.Function, res.Type);
 		}
@@ -596,7 +596,7 @@ namespace MoonSharp.Interpreter.Tests
 				";
 
 
-			RValue res = MoonSharpInterpreter.LoadFromString(script).Execute(null);
+			DynValue res = Script.RunString(script);
 
 			Assert.AreEqual(DataType.String, res.Type);
 			Assert.AreEqual("ciao", res.String);
@@ -619,7 +619,7 @@ namespace MoonSharp.Interpreter.Tests
 				";
 
 
-			RValue res = MoonSharpInterpreter.LoadFromString(script).Execute(null);
+			DynValue res = Script.RunString(script);
 
 			Assert.AreEqual(DataType.Table, res.Type);
 
@@ -640,7 +640,7 @@ namespace MoonSharp.Interpreter.Tests
 				";
 
 
-			RValue res = MoonSharpInterpreter.LoadFromString(script).Execute(null);
+			DynValue res = Script.RunString(script);
 
 			Assert.AreEqual(DataType.Tuple, res.Type);
 			Assert.AreEqual(DataType.Number, res.Tuple[0].Type);
@@ -662,7 +662,7 @@ namespace MoonSharp.Interpreter.Tests
 						Allowed();
 								";
 
-			RValue res = MoonSharpInterpreter.LoadFromString(script).Execute(null);
+			DynValue res = Script.RunString(script);
 
 		}
 		[Test]
@@ -679,7 +679,7 @@ namespace MoonSharp.Interpreter.Tests
 						Allowed();
 								";
 
-			RValue res = MoonSharpInterpreter.LoadFromString(script).Execute(null);
+			DynValue res = Script.RunString(script);
 
 		}
 
@@ -700,7 +700,7 @@ namespace MoonSharp.Interpreter.Tests
 						Allowed();
 								";
 
-			RValue res = MoonSharpInterpreter.LoadFromString(script).Execute(null);
+			DynValue res = Script.RunString(script);
 
 		}
 
@@ -716,9 +716,9 @@ namespace MoonSharp.Interpreter.Tests
 					do return x(); end
 								";
 
-			RValue res = MoonSharpInterpreter.LoadFromString(script).Execute(null);
+			DynValue res = Script.RunString(script);
 
-			Assert.AreEqual(DataType.Number, res);
+			Assert.AreEqual(DataType.Number, res.Type);
 			Assert.AreEqual(1, res.Number);
 		}
 
@@ -733,9 +733,9 @@ namespace MoonSharp.Interpreter.Tests
 					return 1,x(),x()
 								";
 
-			RValue res = MoonSharpInterpreter.LoadFromString(script).Execute(null);
+			DynValue res = Script.RunString(script);
 
-			Assert.AreEqual(DataType.Tuple, res);
+			Assert.AreEqual(DataType.Tuple, res.Type);
 			Assert.AreEqual(4, res.Tuple.Length);
 		}
 
@@ -756,7 +756,7 @@ namespace MoonSharp.Interpreter.Tests
 					return x(a, b+1), a, b;
 								";
 
-			RValue res = MoonSharpInterpreter.LoadFromString(script).Execute(null);
+			DynValue res = Script.RunString(script);
 
 			Assert.AreEqual(3, res.Tuple.Length);
 			Assert.AreEqual(DataType.Number, res.Tuple[0].Type);

+ 12 - 12
src/MoonSharp.Interpreter.Tests/EndToEnd/TableTests.cs

@@ -21,7 +21,7 @@ namespace MoonSharp.Interpreter.Tests
 
 						return a[1]";
 
-			RValue res = MoonSharpInterpreter.LoadFromString(script).Execute(null);
+			DynValue res = Script.RunString(script);
 
 			Assert.AreEqual(DataType.Number, res.Type);
 			Assert.AreEqual(1, res.Number);
@@ -41,7 +41,7 @@ namespace MoonSharp.Interpreter.Tests
 
 						return a[1], a[2], a[3], a['ciao'], a.hello, a.aurevoir, a[false]";
 
-			RValue res = MoonSharpInterpreter.LoadFromString(script).Execute(null);
+			DynValue res = Script.RunString(script);
 
 			Assert.AreEqual(DataType.Tuple, res.Type);
 			Assert.AreEqual(7, res.Tuple.Length);
@@ -80,7 +80,7 @@ namespace MoonSharp.Interpreter.Tests
 
 						return x";
 
-			RValue res = MoonSharpInterpreter.LoadFromString(script).Execute(null);
+			DynValue res = Script.RunString(script);
 
 			Assert.AreEqual(DataType.Number, res.Type);
 			Assert.AreEqual(1994, res.Number);
@@ -105,7 +105,7 @@ namespace MoonSharp.Interpreter.Tests
 
 						return x";
 
-			RValue res = MoonSharpInterpreter.LoadFromString(script).Execute(null);
+			DynValue res = Script.RunString(script);
 
 			Assert.AreEqual(DataType.Number, res.Type);
 			Assert.AreEqual(1994, res.Number);
@@ -130,7 +130,7 @@ namespace MoonSharp.Interpreter.Tests
 
 						return x";
 
-			RValue res = MoonSharpInterpreter.LoadFromString(script).Execute(null);
+			DynValue res = Script.RunString(script);
 
 			Assert.AreEqual(DataType.Number, res.Type);
 			Assert.AreEqual(1994, res.Number);
@@ -156,7 +156,7 @@ namespace MoonSharp.Interpreter.Tests
 
 						return x";
 
-			RValue res = MoonSharpInterpreter.LoadFromString(script).Execute(null);
+			DynValue res = Script.RunString(script);
 
 			Assert.AreEqual(DataType.Number, res.Type);
 			Assert.AreEqual(1994, res.Number);
@@ -184,7 +184,7 @@ namespace MoonSharp.Interpreter.Tests
 
 						return x";
 
-			RValue res = MoonSharpInterpreter.LoadFromString(script).Execute(null);
+			DynValue res = Script.RunString(script);
 
 			Assert.AreEqual(DataType.Number, res.Type);
 			Assert.AreEqual(1994, res.Number);
@@ -201,10 +201,10 @@ namespace MoonSharp.Interpreter.Tests
 						  return (a:add(10):add(20):add(30).x == 60 and a.y == 20)
 						end";
 
-			RValue res = MoonSharpInterpreter.LoadFromString(script).Execute(null);
+			DynValue res = Script.RunString(script);
 
 			Assert.AreEqual(DataType.Boolean, res.Type);
-			Assert.AreEqual(true, res.TestAsBoolean());
+			Assert.AreEqual(true, res.CastToBool());
 		}
 
 		[Test]
@@ -251,7 +251,7 @@ namespace MoonSharp.Interpreter.Tests
 
 			globalCtx.RegisterModuleType<TableIterators>();
 
-			RValue res = MoonSharpInterpreter.LoadFromString(script).Execute(globalCtx);
+			DynValue res = (new Script(globalCtx)).DoString(script);
 
 			Assert.AreEqual(DataType.String, res.Type);
 			Assert.AreEqual("1|2|3|4|5", res.String);
@@ -285,7 +285,7 @@ namespace MoonSharp.Interpreter.Tests
 
 			globalCtx.RegisterModuleType<TableIterators>();
 
-			RValue res = MoonSharpInterpreter.LoadFromString(script).Execute(globalCtx);
+			DynValue res = (new Script(globalCtx)).DoString(script);
 
 			Assert.AreEqual(DataType.Tuple, res.Type);
 			Assert.AreEqual(DataType.String, res.Tuple[0].Type);
@@ -318,7 +318,7 @@ namespace MoonSharp.Interpreter.Tests
 
 			globalCtx.RegisterModuleType<TableIterators>();
 
-			RValue res = MoonSharpInterpreter.LoadFromString(script).Execute(globalCtx);
+			DynValue res = (new Script(globalCtx)).DoString(script);
 
 			Assert.AreEqual(DataType.Tuple, res.Type);
 			Assert.AreEqual(2, res.Tuple.Length);

+ 7 - 7
src/MoonSharp.Interpreter.Tests/EndToEnd/TailCallTests.cs

@@ -22,16 +22,16 @@ namespace MoonSharp.Interpreter.Tests.EndToEnd
 
 
 			var globalCtx = new Table();
-			globalCtx[new RValue("clrtail")] = new RValue(new CallbackFunction((xc, a) =>
+			globalCtx["clrtail"] = DynValue.NewCallback((xc, a) =>
 			{
-				LRef lref = LRef.Global("getResult");
-				RValue fn = xc.GetVar(lref);
-				RValue k3 = new RValue(a[0].Number / 3);
+				SymbolRef lref = SymbolRef.Global("getResult");
+				DynValue fn = xc.GetVar(lref);
+				DynValue k3 = DynValue.NewNumber(a[0].Number / 3);
 
-				return new RValue(fn, k3);
-			}));
+				return DynValue.NewTailCallReq(fn, k3);
+			});
 
-			var res = MoonSharpInterpreter.LoadFromString(script).Execute(globalCtx);
+			var res = (new Script(globalCtx)).DoString(script);
 
 			Assert.AreEqual(DataType.Number, res.Type);
 			Assert.AreEqual(468, res.Number);

+ 9 - 6
src/MoonSharp.Interpreter.Tests/TestMore/TapRunner.cs

@@ -3,6 +3,7 @@ using System.Collections.Generic;
 using System.IO;
 using System.Linq;
 using System.Text;
+using MoonSharp.Interpreter.CoreLib;
 using MoonSharp.Interpreter.Execution;
 using NUnit.Framework;
 
@@ -12,11 +13,11 @@ namespace MoonSharp.Interpreter.Tests
 	{
 		string m_File;
 
-		public RValue Print(IExecutionContext exctx, CallbackArguments values)
+		public DynValue Print(IExecutionContext exctx, CallbackArguments values)
 		{
-			string str = string.Join(" ", values.List.Select(s => s.AsString()).ToArray());
+			string str = string.Join(" ", values.List.Select(s => s.ToPrintString()).ToArray());
 			Assert.IsFalse(str.Trim().StartsWith("not ok"), string.Format("TAP fail ({0}) : {1}", m_File, str));
-			return RValue.Nil;
+			return DynValue.Nil;
 		}
 
 		public TapRunner(string filename)
@@ -28,9 +29,11 @@ namespace MoonSharp.Interpreter.Tests
 		{
 			string script = File.ReadAllText(m_File);
 			var globalCtx = new Table();
-			globalCtx[new RValue("print")] = new RValue(new CallbackFunction(Print));
-			globalCtx[new RValue("arg")] = new RValue(new Table());
-			MoonSharpInterpreter.LoadFromString(script).Execute(globalCtx);
+			globalCtx["print"] = DynValue.NewCallback(Print);
+			globalCtx["arg"] = DynValue.NewTable();
+			globalCtx.RegisterModuleType<TableIterators>();
+			globalCtx.RegisterModuleType<MetaTableMethods>();
+			(new Script(globalCtx)).DoString(script);
 		}
 
 		public static void Run(string filename)

+ 1 - 1
src/MoonSharp.Interpreter.Tests/TestMore/TestMoreTests.cs

@@ -51,7 +51,7 @@ namespace MoonSharp.Interpreter.Tests
 		}
 
 
-		[Test] [Ignore]
+		[Test] 
 		public void TestMore_015_forlist()
 		{
 			TapRunner.Run(@"TestMore\015-forlist.t");

+ 52 - 29
src/MoonSharp.Interpreter/CoreLib/BasicMethods.cs

@@ -6,37 +6,60 @@ using MoonSharp.Interpreter.Execution;
 
 namespace MoonSharp.Interpreter.CoreLib
 {
+	[MoonSharpModule]
 	public static class BasicMethods
 	{
-		// ALSO TO SUPPORT:
-		// _G, _VERSION, _MOONSHARP
-
-		public static RValue assert(RValue[] values) { return RValue.Nil; }
-		public static RValue collectgarbage(RValue[] values) { return RValue.Nil; }
-		public static RValue error(RValue[] values) { return RValue.Nil; }
-		public static RValue pcall(RValue[] values) { return RValue.Nil; }
-		public static RValue xpcall(RValue[] values) { return RValue.Nil; }
-		public static RValue print(RValue[] values) { return RValue.Nil; }
-		public static RValue select(RValue[] values) { return RValue.Nil; }
-		public static RValue tonumber(RValue[] values) { return RValue.Nil; }
-		public static RValue tostring(RValue[] values) { return RValue.Nil; }
-		public static RValue type(RValue[] values) { return RValue.Nil; }
-
-
-
-
-
-
-
-
-		// Unsupported (?) - will raise exceptions:
-		public static RValue load(RValue[] values) { return RValue.Nil; }
-		public static RValue loadfile(RValue[] values) { return RValue.Nil; }
-		public static RValue dofile(RValue[] values) { return RValue.Nil; }
-
-
-
-
+		//assert (v [, message])
+		//----------------------------------------------------------------------------------------------------------------
+		//Issues an error when the value of its argument v is false (i.e., nil or false); 
+		//otherwise, returns all its arguments. message is an error message; when absent, it defaults to "assertion failed!" 
+		[MoonSharpMethod]
+		public static DynValue assert(IExecutionContext executionContext, CallbackArguments args)
+		{
+			DynValue v = args[0];
+			DynValue message = args[1];
+
+			if (!v.CastToBool())
+			{
+				if (message.IsNil())
+					throw new ScriptRuntimeException(null, "assertion failed!");
+				else
+					throw new ScriptRuntimeException(null, message.ToPrintString());
+			}
+
+			return DynValue.Nil;
+		}
+
+		// collectgarbage  ([opt [, arg]])
+		// ----------------------------------------------------------------------------------------------------------------
+		// This function is mostly a stub towards the CLR GC. If mode is nil, "collect" or "restart", a GC is forced.
+		[MoonSharpMethod]
+		public static DynValue collectgarbage(IExecutionContext executionContext, CallbackArguments args)
+		{
+			DynValue opt = args[0];
+
+			string mode = opt.CastToString();
+
+			if (mode == null || mode == "collect" || mode == "restart")
+				GC.Collect();
+
+			return DynValue.Nil;
+		}
+
+		// error (message [, level])
+		// ----------------------------------------------------------------------------------------------------------------
+		// Terminates the last protected function called and returns message as the error message. Function error never returns.
+		// Usually, error adds some information about the error position at the beginning of the message. 
+		// The level argument specifies how to get the error position. 
+		// With level 1 (the default), the error position is where the error function was called. 
+		// Level 2 points the error to where the function that called error was called; and so on. 
+		// Passing a level 0 avoids the addition of error position information to the message. 
+		[MoonSharpMethod]
+		public static DynValue error(IExecutionContext executionContext, CallbackArguments args)
+		{
+			DynValue message = args.AsType(0, "dofile", DataType.String, false);
+			throw new ScriptRuntimeException(null, message.String);
+		}
 
 
 	}

+ 0 - 35
src/MoonSharp.Interpreter/CoreLib/CoreLibModule.cs

@@ -1,35 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using MoonSharp.Interpreter.CoreLib;
-using MoonSharp.Interpreter.Execution;
-
-namespace MoonSharp.Interpreter
-{
-	[Flags]
-	public enum CoreLibModules
-	{
-		TableIterators = 0x1,
-		Metatables = 0x2,
-
-
-		Default_HardSandbox = TableIterators,
-		Default_SoftSandbox = Default_HardSandbox | Metatables,
-		Default = Default_SoftSandbox,
-	}
-
-	public static class CoreLib_Ext
-	{
-		public static Table RegisterCoreModules(this Table t, CoreLibModules modules = CoreLibModules.Default)
-		{
-			if ((modules & CoreLibModules.TableIterators) != 0)
-				t.RegisterModuleType<TableIterators>();
-
-
-			return t;
-		}
-
-	}
-
-}

+ 11 - 0
src/MoonSharp.Interpreter/CoreLib/ErrorHandling.cs

@@ -0,0 +1,11 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+
+namespace MoonSharp.Interpreter.CoreLib
+{
+	class ErrorHandling
+	{
+	}
+}

+ 61 - 0
src/MoonSharp.Interpreter/CoreLib/LoadMethods.cs

@@ -0,0 +1,61 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using MoonSharp.Interpreter.Execution;
+
+namespace MoonSharp.Interpreter.CoreLib
+{
+	[MoonSharpModule]
+	public class LoadMethods
+	{
+		//dofile ([filename])
+		//--------------------------------------------------------------------------------------------------------------
+		//Opens the named file and executes its contents as a Lua chunk. When called without arguments, 
+		//dofile executes the contents of the standard input (stdin). Returns all values returned by the chunk. 
+		//In case of errors, dofile propagates the error to its caller (that is, dofile does not run in protected mode). 
+		[MoonSharpMethod]
+		public static DynValue dofile(IExecutionContext executionContext, CallbackArguments args)
+		{
+			Script S = executionContext.GetOwnerScript();
+			DynValue v = args.AsType(0, "dofile", DataType.String, false);
+
+			DynValue fn = S.LoadFile(v.String);
+
+			return DynValue.NewTailCallReq(fn); // tail call to dofile
+		}
+
+		//require (modname)
+		//----------------------------------------------------------------------------------------------------------------
+		//Loads the given module. The function starts by looking into the package.loaded table to determine whether 
+		//modname is already loaded. If it is, then require returns the value stored at package.loaded[modname]. 
+		//Otherwise, it tries to find a loader for the module.
+		//
+		//To find a loader, require is guided by the package.loaders array. By changing this array, we can change 
+		//how require looks for a module. The following explanation is based on the default configuration for package.loaders.
+		//
+		//First require queries package.preload[modname]. If it has a value, this value (which should be a function) 
+		//is the loader. Otherwise require searches for a Lua loader using the path stored in package.path. 
+		//If that also fails, it searches for a C loader using the path stored in package.cpath. If that also fails, 
+		//it tries an all-in-one loader (see package.loaders).
+		//
+		//Once a loader is found, require calls the loader with a single argument, modname. If the loader returns any value, 
+		//require assigns the returned value to package.loaded[modname]. If the loader returns no value and has not assigned 
+		//any value to package.loaded[modname], then require assigns true to this entry. In any case, require returns the 
+		//final value of package.loaded[modname].
+		//
+		//If there is any error loading or running the module, or if it cannot find any loader for the module, then require 
+		//signals an error. 
+		[MoonSharpMethod]
+		public static DynValue require(IExecutionContext executionContext, CallbackArguments args)
+		{
+			Script S = executionContext.GetOwnerScript();
+			DynValue v = args.AsType(0, "dofile", DataType.String, false);
+
+			DynValue fn = S.LoadFile(v.String);
+
+			return DynValue.NewTailCallReq(fn); // tail call to dofile
+		}
+
+	}
+}

+ 21 - 21
src/MoonSharp.Interpreter/CoreLib/MetaTableMethods.cs

@@ -16,12 +16,12 @@ namespace MoonSharp.Interpreter.CoreLib
 		// If the original metatable has a "__metatable" field, raises an error ("cannot change a protected metatable").
 		// This function returns table. 
 		[MoonSharpMethod]
-		public static RValue setmetatable(IExecutionContext executionContext, CallbackArguments args)  
+		public static DynValue setmetatable(IExecutionContext executionContext, CallbackArguments args)  
 		{
-			RValue table = args.AsType(0, "setmetatable", DataType.Table);
-			RValue metatable = args.AsType(1, "setmetatable", DataType.Table, true);
+			DynValue table = args.AsType(0, "setmetatable", DataType.Table);
+			DynValue metatable = args.AsType(1, "setmetatable", DataType.Table, true);
 
-			RValue curmeta = executionContext.GetMetamethod(table, "__metatable");
+			DynValue curmeta = executionContext.GetMetamethod(table, "__metatable");
 
 			if (curmeta != null)
 			{
@@ -37,31 +37,31 @@ namespace MoonSharp.Interpreter.CoreLib
 		// If object does not have a metatable, returns nil. Otherwise, if the object's metatable 
 		// has a "__metatable" field, returns the associated value. Otherwise, returns the metatable of the given object. 
 		[MoonSharpMethod]
-		public static RValue getmetatable(IExecutionContext executionContext, CallbackArguments args)  
+		public static DynValue getmetatable(IExecutionContext executionContext, CallbackArguments args)  
 		{
-			RValue obj = args[0];
+			DynValue obj = args[0];
 
 			if (obj.Type == DataType.Nil)
-				return RValue.Nil;
+				return DynValue.Nil;
 
-			RValue curmeta = executionContext.GetMetamethod(obj, "__metatable");
+			DynValue curmeta = executionContext.GetMetamethod(obj, "__metatable");
 
 			if (curmeta != null)
 			{
 				return curmeta;
 			}
 
-			return obj.Meta ?? RValue.Nil;
+			return obj.Meta ?? DynValue.Nil;
 		}
 
 		// rawget (table, index)
 		// -------------------------------------------------------------------------------------------------------------------
 		// Gets the real value of table[index], without invoking any metamethod. table must be a table; index may be any value.
 		[MoonSharpMethod]
-		public static RValue rawget(IExecutionContext executionContext, CallbackArguments args)  
+		public static DynValue rawget(IExecutionContext executionContext, CallbackArguments args)  
 		{
-			RValue table = args.AsType(0, "rawget", DataType.Table);
-			RValue index = args[1];
+			DynValue table = args.AsType(0, "rawget", DataType.Table);
+			DynValue index = args[1];
 
 			return table.Table[index];
 		}
@@ -72,10 +72,10 @@ namespace MoonSharp.Interpreter.CoreLib
 		// index any value different from nil and NaN, and value any Lua value.
 		// This function returns table. 
 		[MoonSharpMethod]
-		public static RValue rawset(IExecutionContext executionContext, CallbackArguments args)  
+		public static DynValue rawset(IExecutionContext executionContext, CallbackArguments args)  
 		{
-			RValue table = args.AsType(0, "rawset", DataType.Table);
-			RValue index = args[1];
+			DynValue table = args.AsType(0, "rawset", DataType.Table);
+			DynValue index = args[1];
 
 			table.Table[index] = args[2];
 
@@ -86,21 +86,21 @@ namespace MoonSharp.Interpreter.CoreLib
 		// -------------------------------------------------------------------------------------------------------------------
 		// Checks whether v1 is equal to v2, without invoking any metamethod. Returns a boolean. 
 		[MoonSharpMethod]
-		public static RValue rawequal(IExecutionContext executionContext, CallbackArguments args)  
+		public static DynValue rawequal(IExecutionContext executionContext, CallbackArguments args)  
 		{
-			RValue v1 = args[0];
-			RValue v2 = args[1];
+			DynValue v1 = args[0];
+			DynValue v2 = args[1];
 
-			return new RValue(v1.Equals(v2)); 
+			return DynValue.NewBoolean(v1.Equals(v2)); 
 		}
 
 		//rawlen (v)
 		// -------------------------------------------------------------------------------------------------------------------
 		//Returns the length of the object v, which must be a table or a string, without invoking any metamethod. Returns an integer number.	
 		[MoonSharpMethod]
-		public static RValue rawlen(IExecutionContext executionContext, CallbackArguments args) 
+		public static DynValue rawlen(IExecutionContext executionContext, CallbackArguments args) 
 		{
-			return new RValue(args[0].GetLength());
+			return args[0].GetLength();
 		}
 
 

+ 18 - 18
src/MoonSharp.Interpreter/CoreLib/TableIterators.cs

@@ -17,13 +17,13 @@ namespace MoonSharp.Interpreter.CoreLib
 		//	  for i,v in ipairs(t) do body end
 		// will iterate over the pairs (1,t[1]), (2,t[2]), ..., up to the first integer key absent from the table. 
 		[MoonSharpMethod]
-		static RValue ipairs(IExecutionContext executionContext, CallbackArguments args) 
+		static DynValue ipairs(IExecutionContext executionContext, CallbackArguments args) 
 		{
-			RValue table = args[0];
+			DynValue table = args[0];
 
-			RValue meta = executionContext.GetMetamethodTailCall(table, "__ipairs", args.ToArray());
+			DynValue meta = executionContext.GetMetamethodTailCall(table, "__ipairs", args.ToArray());
 
-			return meta ?? new RValue(new RValue[] { new RValue(new CallbackFunction(__next_i)), table, new RValue(0) });
+			return meta ?? DynValue.NewTuple(DynValue.NewCallback(__next_i), table, DynValue.NewNumber(0));
 		}
 
 		// pairs (t)
@@ -34,13 +34,13 @@ namespace MoonSharp.Interpreter.CoreLib
 		// will iterate over all key–value pairs of table t.
 		// See function next for the caveats of modifying the table during its traversal. 
 		[MoonSharpMethod]
-		static RValue pairs(IExecutionContext executionContext, CallbackArguments args) 
+		static DynValue pairs(IExecutionContext executionContext, CallbackArguments args) 
 		{
-			RValue table = args[0];
+			DynValue table = args[0];
 
-			RValue meta = executionContext.GetMetamethodTailCall(table, "__pairs", args.ToArray());
+			DynValue meta = executionContext.GetMetamethodTailCall(table, "__pairs", args.ToArray());
 
-			return meta ?? new RValue(new RValue[] { new RValue(new CallbackFunction(next)), table });
+			return meta ?? DynValue.NewTuple(DynValue.NewCallback(next), table);
 		}
 
 		// next (table [, index])
@@ -55,34 +55,34 @@ namespace MoonSharp.Interpreter.CoreLib
 		// The behavior of next is undefined if, during the traversal, you assign any value to a non-existent field in the table. 
 		// You may however modify existing fields. In particular, you may clear existing fields. 
 		[MoonSharpMethod]
-		static RValue next(IExecutionContext executionContext, CallbackArguments args) 
+		static DynValue next(IExecutionContext executionContext, CallbackArguments args) 
 		{
-			RValue table = args.AsType(0, "next", DataType.Table);
-			RValue index = args[1];
+			DynValue table = args.AsType(0, "next", DataType.Table);
+			DynValue index = args[1];
 
 			TablePair pair = table.Table.NextKey(index);
 
-			return new RValue(new RValue[] { pair.Key, pair.Value });
+			return DynValue.NewTuple(pair.Key, pair.Value);
 		}
 
 		// __next_i (table [, index])
 		// -------------------------------------------------------------------------------------------------------------------
 		// Allows a program to traverse all fields of an array. index is an integer number
-		static RValue __next_i(IExecutionContext executionContext, CallbackArguments args) 
+		static DynValue __next_i(IExecutionContext executionContext, CallbackArguments args) 
 		{
-			RValue table = args.AsType(0, "!!next_i!!", DataType.Table);
-			RValue index = args.AsType(1, "!!next_i!!", DataType.Number);
+			DynValue table = args.AsType(0, "!!next_i!!", DataType.Table);
+			DynValue index = args.AsType(1, "!!next_i!!", DataType.Number);
 
 			int idx = ((int)index.Number) + 1;
-			RValue val = table.Table[idx];
+			DynValue val = table.Table[idx];
 			
 			if (val.Type != DataType.Nil)
 			{
-				return new RValue(new RValue[] { new RValue(idx), val });
+				return DynValue.NewTuple(DynValue.NewNumber(idx), val);
 			}
 			else
 			{
-				return RValue.Nil;
+				return DynValue.Nil;
 			}
 		}
 	}

+ 1 - 1
src/MoonSharp.Interpreter/Debugging/IDebugger.cs

@@ -8,7 +8,7 @@ namespace MoonSharp.Interpreter.Debugging
 {
 	public interface IDebugger
 	{
-		void SetSourceCode(Chunk byteCode, string[] code);
+		void SetSourceCode(ByteCode byteCode, string[] code);
 		DebuggerAction GetAction(int ip);
 		void Update(WatchType watchType, List<WatchItem> items);
 		List<string> GetWatchItems();

+ 2 - 2
src/MoonSharp.Interpreter/Debugging/WatchItem.cs

@@ -12,7 +12,7 @@ namespace MoonSharp.Interpreter.Debugging
 		public int BasePtr { get; set; }
 		public int RetAddress { get; set; }
 		public string Name { get; set; }
-		public RValue Value { get; set; }
-		public LRef LValue { get; set; }
+		public DynValue Value { get; set; }
+		public SymbolRef LValue { get; set; }
 	}
 }

+ 7 - 7
src/MoonSharp.Interpreter/Execution/DataTypes/CallbackArguments.cs

@@ -7,9 +7,9 @@ namespace MoonSharp.Interpreter.Execution
 {
 	public class CallbackArguments
 	{
-		IList<RValue> m_Args;
+		IList<DynValue> m_Args;
 
-		public CallbackArguments(IList<RValue> args)
+		public CallbackArguments(IList<DynValue> args)
 		{
 			m_Args = args;
 		}
@@ -19,20 +19,20 @@ namespace MoonSharp.Interpreter.Execution
 			get { return m_Args.Count; }
 		}
 
-		public RValue this[int index]
+		public DynValue this[int index]
 		{
 			get 
 			{
 				if (index < m_Args.Count)
 					return m_Args[index];
 
-				return RValue.Nil;
+				return DynValue.Nil;
 			}
 		}
 
-		public IList<RValue> List { get { return m_Args; } }
+		public IList<DynValue> List { get { return m_Args; } }
 
-		public RValue[] ToArray()
+		public DynValue[] ToArray()
 		{
 			return List.ToArray();
 		}
@@ -44,7 +44,7 @@ namespace MoonSharp.Interpreter.Execution
 				argNum + 1, funcName, expected, got);
 		}
 
-		public RValue AsType(int argNum, string funcName, DataType type, bool allowNil = false)
+		public DynValue AsType(int argNum, string funcName, DataType type, bool allowNil = false)
 		{
 			if (allowNil && this[argNum].Type == DataType.Nil)
 				return this[argNum];

+ 3 - 3
src/MoonSharp.Interpreter/Execution/DataTypes/CallbackFunction.cs

@@ -7,14 +7,14 @@ namespace MoonSharp.Interpreter.Execution
 {
 	public sealed class CallbackFunction
 	{
-		Func<IExecutionContext, CallbackArguments, RValue> m_CallBack;
+		Func<IExecutionContext, CallbackArguments, DynValue> m_CallBack;
 
-		public CallbackFunction(Func<IExecutionContext, CallbackArguments, RValue> callBack)
+		public CallbackFunction(Func<IExecutionContext, CallbackArguments, DynValue> callBack)
 		{
 			m_CallBack = callBack;
 		}
 
-		public RValue Invoke(IExecutionContext executionContext, IList<RValue> args)
+		public DynValue Invoke(IExecutionContext executionContext, IList<DynValue> args)
 		{
 			return m_CallBack(executionContext, new  CallbackArguments(args));
 		}

+ 3 - 1
src/MoonSharp.Interpreter/Execution/DataTypes/Closure.cs

@@ -11,10 +11,12 @@ namespace MoonSharp.Interpreter.Execution
 
 		public ClosureContext ClosureContext { get; private set; }
 
+		public Table GlobalEnv { get; set; }
+
 		private static ClosureContext emptyClosure = new ClosureContext();
 
 
-		internal Closure(int idx, LRef[] symbols, RValue[] localscope)
+		internal Closure(int idx, SymbolRef[] symbols, DynValue[] localscope)
 		{
 			ByteCodeLocation = idx;
 

+ 0 - 73
src/MoonSharp.Interpreter/Execution/DataTypes/LRef.cs

@@ -1,73 +0,0 @@
-using System;
-using System.Collections.Generic;
-using MoonSharp.Interpreter.Diagnostics;
-using System.Linq;
-using System.Text;
-
-namespace MoonSharp.Interpreter.Execution
-{
-	/// <summary>
-	/// This class stores a possible l-value (that is a potential target of an assignment)
-	/// </summary>
-	public class LRef
-	{
-		// Fields are internal - direct access by the executor was a 10% improvement at profiling here!
-		internal LRefType i_Type;
-		internal int i_Index;
-		internal string i_Name;
-		internal RValue i_TableRefObject;
-		internal RValue i_TableRefIndex;
-
-		public LRefType Type { get { return i_Type; } }
-		public int Index { get { return i_Index; } }
-		public string Name { get { return i_Name; } }
-		public RValue TableRefObject { get { return i_TableRefObject; } }
-		public RValue TableRefIndex { get { return i_TableRefIndex; } } 
-
-
-
-		public static LRef Global(string name)
-		{
-			return new LRef() { i_Index = -1, i_Type = LRefType.Global, i_Name = name };
-		}
-
-		public static LRef Local(string name, int index)
-		{
-			return new LRef() { i_Index = index, i_Type = LRefType.Local, i_Name = name };
-		}
-
-		public static LRef Upvalue(string name, int index)
-		{
-			return new LRef() { i_Index = index, i_Type = LRefType.Upvalue, i_Name = name };
-		}
-		public static LRef Argument(string name, int index)
-		{
-			return new LRef() { i_Index = index, i_Type = LRefType.Argument, i_Name = name };
-		}
-
-		public static LRef Invalid()
-		{
-			return new LRef() { i_Index = -1, i_Type = LRefType.Invalid, i_Name = "!INV!" };
-		}
-
-		public static LRef ObjIndex(RValue baseObject, RValue indexObject)
-		{
-			return new LRef() { i_TableRefObject = baseObject, i_TableRefIndex = indexObject, i_Type = LRefType.Index };
-		}
-
-		public bool IsValid()
-		{
-			return i_Type !=  LRefType.Invalid;
-		}
-
-
-		public override string ToString()
-		{
-			return string.Format("{0}[{1}] : {2}", i_Type, i_Index, i_Name);
-		}
-
-
-
-
-	}
-}

+ 0 - 450
src/MoonSharp.Interpreter/Execution/DataTypes/RValue.cs

@@ -1,450 +0,0 @@
-using System;
-using System.Collections.Generic;
-using MoonSharp.Interpreter.Diagnostics;
-using System.Globalization;
-using System.Linq;
-using System.Text;
-using System.Threading;
-
-namespace MoonSharp.Interpreter.Execution
-{
-	public sealed class RValue
-	{
-		static int s_RefIDCounter = 0;
-		private int m_RefID = ++s_RefIDCounter;
-
-		public int ReferenceID { get { return m_RefID; } }
-
-		public DataType Type { get; private set; }
-		public Closure Function { get; private set; }
-		public double Number { get; private set; }
-		public RValue[] Tuple { get; private set; }
-		public Table Table { get; private set; }
-		public bool Boolean { get; private set; }
-		public string String { get; private set; }
-		public bool ReadOnly { get; internal set; }
-		public LRef Symbol { get; private set; }
-		public CallbackFunction Callback { get; set; }
-		public RValue Meta { get; set; }
-
-		private int m_HashCode = -1;
-
-		public RValue()
-		{
-			Type = DataType.Nil;
-		}
-
-		public RValue(bool v)
-		{
-			Boolean = v;
-			Type = DataType.Boolean;
-		}
-		public RValue(double num)
-		{
-			Number = num;
-			Type = DataType.Number;
-			m_HashCode = -1;
-		}
-
-		public RValue(LRef symbol)
-		{
-			this.Symbol = symbol;
-			this.Type = DataType.Symbol;
-		}
-
-		public RValue(string str)
-		{
-			String = str;
-			Type = DataType.String;
-			m_HashCode = -1;
-		}
-
-
-		public RValue(Closure function)
-		{
-			Function = function;
-			Type = DataType.Function;
-			m_HashCode = -1;
-		}
-
-		public RValue(CallbackFunction function)
-		{
-			Callback = function;
-			Type = DataType.ClrFunction;
-			m_HashCode = -1;
-		}
-
-		public RValue(Table table)
-		{
-			Table = table;
-			Type = DataType.Table;
-			m_HashCode = -1;
-		}
-
-		public RValue(RValue tailFn, params RValue[] args)
-		{
-			Meta = tailFn;
-			Tuple = args;
-			Type = DataType.TailCallRequest;
-		}
-
-		public RValue(RValue[] tuple)
-		{
-			Tuple = tuple;
-			Type = DataType.Tuple;
-			m_HashCode = -1;
-		}
-
-		public RValue AsReadOnly()
-		{
-			if (ReadOnly)
-				return this;
-			else
-			{
-				RValue v = Clone();
-				v.ReadOnly = true;
-				return v;
-			}
-		}
-
-		public RValue Clone()
-		{
-			if (this.Type == DataType.Symbol)
-				throw new ArgumentException("Can't clone Symbol values");
-
-			RValue v = new RValue();
-			v.Boolean = this.Boolean;
-			v.Callback = this.Callback;
-			v.Function = this.Function;
-			v.Number = this.Number;
-			v.ReadOnly = this.ReadOnly;
-			v.String = this.String;
-			v.Table = this.Table;
-			v.Tuple = this.Tuple;
-			v.Type = this.Type;
-			v.Meta = this.Meta;
-			v.m_HashCode = this.m_HashCode;
-			return v;
-		}
-
-		public RValue CloneAsWritable()
-		{
-			if (this.Type == DataType.Symbol)
-				throw new ArgumentException("Can't clone Symbol values");
-
-			RValue v = new RValue();
-			v.Boolean = this.Boolean;
-			v.Function = this.Function;
-			v.Callback = this.Callback;
-			v.Number = this.Number;
-			v.ReadOnly = false;
-			v.String = this.String;
-			v.Table = this.Table;
-			v.Tuple = this.Tuple;
-			v.Type = this.Type;
-			v.Meta = this.Meta;
-			v.m_HashCode = this.m_HashCode;
-			return v;
-		}
-
-
-		public static RValue Nil { get; private set; }
-		public static RValue True { get; private set; }
-		public static RValue False { get; private set; }
-		static RValue()
-		{
-			Nil = new RValue().AsReadOnly();
-			True = new RValue(true).AsReadOnly();
-			False = new RValue(false).AsReadOnly();
-		}
-
-		public string AsSimpleString()
-		{
-			RValue rv = ToSimplestValue();
-			if (rv.Type == DataType.Number)
-			{
-				return rv.Number.ToString();
-			}
-			else if (rv.Type == DataType.String)
-			{
-				return rv.String;
-			}
-			return null;
-		}
-
-
-
-		public string AsString()
-		{
-			switch (Type)
-			{
-				case DataType.String:
-					return String;
-				case DataType.Table:
-					return "(Table)";
-				case DataType.Tuple:
-					return string.Join("\t", Tuple.Select(t => t.AsString()).ToArray());
-				case DataType.Symbol:
-					return "(Symbol -- INTERNAL!)";
-				case DataType.TailCallRequest:
-					return "(TailCallRequest -- INTERNAL!)";
-				case DataType.UserData:
-					return "(UserData)";
-				case DataType.Thread:
-					return "(Thread)";
-				default:
-					return ToString();
-			}
-		}
-
-		public override string ToString()
-		{
-			switch (Type)
-			{
-				case DataType.Nil:
-					return "nil";
-				case DataType.Boolean:
-					return Boolean.ToString().ToLower();
-				case DataType.Number:
-					return Number.ToString();
-				case DataType.String:
-					return "\"" + String + "\"";
-				case DataType.Function:
-					return string.Format("(Function {0:X8})", Function.ByteCodeLocation);
-				case DataType.ClrFunction:
-					return string.Format("(Function CLR)", Function);
-				case DataType.Table:
-					return "(Table)";
-				case DataType.Tuple:
-					return string.Join(", ", Tuple.Select(t => t.ToString()).ToArray());
-				case DataType.TailCallRequest:
-					return "Tail:(" + string.Join(", ", Tuple.Select(t => t.ToString()).ToArray()) + ")";
-				case DataType.Symbol:
-					return Symbol.ToString();
-				case DataType.UserData:
-					return "(UserData)";
-				case DataType.Thread:
-					return "(Thread)";
-				default:
-					return "(???)";
-			}
-		}
-
-		public override int GetHashCode()
-		{
-			if (m_HashCode != -1)
-				return m_HashCode;
-
-			int baseValue = ((int)(Type)) << 27;
-
-			switch (Type)
-			{
-				case DataType.Nil:
-					m_HashCode = 0;
-					break;
-				case DataType.Boolean:
-					m_HashCode = Boolean ? 1 : 2;
-					break;
-				case DataType.Number:
-					m_HashCode = baseValue ^ Number.GetHashCode();
-					break;
-				case DataType.String:
-					m_HashCode = baseValue ^ String.GetHashCode();
-					break;
-				case DataType.Function:
-					m_HashCode = baseValue ^ Function.GetHashCode();
-					break;
-				case DataType.ClrFunction:
-					m_HashCode = baseValue ^ Callback.GetHashCode();
-					break;
-				case DataType.Table:
-					m_HashCode = baseValue ^ Table.GetHashCode();
-					break;
-				case DataType.Tuple:
-				case DataType.TailCallRequest:
-					m_HashCode = baseValue ^ Tuple.GetHashCode();
-					break;
-				case DataType.UserData:
-				case DataType.Thread:
-				default:
-					m_HashCode = 999;
-					break;
-			}
-
-			return m_HashCode;
-		}
-
-		public override bool Equals(object obj)
-		{
-			RValue other = obj as RValue;
-
-			if (other == null) return false;
-			if (other.Type != this.Type) return false;
-
-			if (other.Meta != this.Meta) return false;
-
-			switch (Type)
-			{
-				case DataType.Nil:
-					return true;
-				case DataType.Boolean:
-					return Boolean == other.Boolean;
-				case DataType.Number:
-					return Number == other.Number;
-				case DataType.String:
-					return String == other.String;
-				case DataType.Function:
-					return Function == other.Function;
-				case DataType.ClrFunction:
-					return Callback == other.Callback;
-				case DataType.Table:
-					return Table == other.Table;
-				case DataType.Tuple:
-				case DataType.TailCallRequest:
-					return Tuple == other.Tuple;
-				case DataType.UserData:
-				case DataType.Thread:
-				default:
-					return object.ReferenceEquals(this, other);
-			}
-		}
-
-		public IEnumerable<RValue> UnpackedTuple()
-		{
-			if (this.Type == DataType.Tuple)
-			{
-				return Tuple.SelectMany(rv => rv.UnpackedTuple());
-			}
-			else
-			{
-				return new RValue[] { this };
-			}
-		}
-
-		public static RValue FromPotentiallyNestedTuple(RValue[] values)
-		{
-			return new RValue(values.SelectMany(vv => vv.UnpackedTuple()).ToArray());
-		}
-
-		public RValue[] ToArrayOfValues()
-		{
-			if (Type == DataType.Tuple)
-				return Tuple;
-			else
-				return new RValue[] { this };
-		}
-
-		public double? AsNumber()
-		{
-			RValue rv = ToSimplestValue();
-			if (rv.Type == DataType.Number)
-			{
-				return rv.Number;
-			}
-			else if (rv.Type == DataType.String)
-			{
-				double num;
-				if (double.TryParse(rv.String, NumberStyles.Any, CultureInfo.InvariantCulture, out num))
-					return num;
-			}
-			return null;
-		}
-
-		public RValue AsBoolean()
-		{
-			RValue rv = ToSimplestValue();
-			if (rv.Type == DataType.Boolean)
-				return rv;
-			else return new RValue((rv.Type != DataType.Nil));
-		}
-
-		public bool TestAsBoolean()
-		{
-			RValue rv = ToSimplestValue();
-			if (rv.Type == DataType.Boolean)
-				return rv.Boolean;
-			else return (rv.Type != DataType.Nil);
-		}
-
-		public RValue ToSingleValue()
-		{
-			if (Type != DataType.Tuple)
-				return this;
-
-			if (Tuple.Length == 0)
-				return RValue.Nil;
-
-			return Tuple[0].ToSimplestValue();
-		}
-
-
-
-		public RValue ToSimplestValue()
-		{
-			if (Type != DataType.Tuple)
-				return this;
-
-			if (Tuple.Length == 0)
-				return RValue.Nil;
-
-			if (Tuple.Length == 1)
-				return Tuple[0].ToSimplestValue();
-
-			return this;
-		}
-
-		public void Assign(RValue value)
-		{
-			if (this.ReadOnly)
-				throw new ScriptRuntimeException(null, "Assigning on r-value");
-
-			this.Boolean = value.Boolean;
-			this.Callback = value.Callback;
-			this.Function = value.Function;
-			this.Number = value.Number;
-			this.ReadOnly = false;
-			this.String = value.String;
-			this.Table = value.Table;
-			this.Tuple = value.Tuple;
-			this.Type = value.Type;
-			this.Meta = value.Meta;
-			this.m_HashCode = -1;
-		}
-
-
-
-		public RValue GetLength()
-		{
-			if (this.Type == DataType.Table)
-				return new RValue(this.Table.Length);
-			if (this.Type == DataType.String)
-				return new RValue(this.String.Length);
-
-			throw new ScriptRuntimeException(null, "Can't get length of type {0}", this.Type);
-		}
-
-		public bool IsNil()
-		{
-			return this.Type == DataType.Nil;
-		}
-
-		public bool IsNilOrNan()
-		{
-			return (this.Type == DataType.Nil) || (this.Type == DataType.Number && double.IsNaN(this.Number));
-		}
-
-		internal void AssignNumber(double num)
-		{
-			if (this.ReadOnly)
-				throw new InternalErrorException(null, "Writing on r-value");
-
-			if (this.Type != DataType.Number)
-				throw new InternalErrorException("Can't assign number to type {0}", this.Type);
-			this.Number = num;
-		}
-	}
-
-
-
-
-}

+ 73 - 0
src/MoonSharp.Interpreter/Execution/DataTypes/SymbolRef.cs

@@ -0,0 +1,73 @@
+using System;
+using System.Collections.Generic;
+using MoonSharp.Interpreter.Diagnostics;
+using System.Linq;
+using System.Text;
+
+namespace MoonSharp.Interpreter.Execution
+{
+	/// <summary>
+	/// This class stores a possible l-value (that is a potential target of an assignment)
+	/// </summary>
+	public class SymbolRef
+	{
+		// Fields are internal - direct access by the executor was a 10% improvement at profiling here!
+		internal SymbolRefType i_Type;
+		internal int i_Index;
+		internal string i_Name;
+		internal DynValue i_TableRefObject;
+		internal DynValue i_TableRefIndex;
+
+		public SymbolRefType Type { get { return i_Type; } }
+		public int Index { get { return i_Index; } }
+		public string Name { get { return i_Name; } }
+		public DynValue TableRefObject { get { return i_TableRefObject; } }
+		public DynValue TableRefIndex { get { return i_TableRefIndex; } } 
+
+
+
+		public static SymbolRef Global(string name)
+		{
+			return new SymbolRef() { i_Index = -1, i_Type = SymbolRefType.Global, i_Name = name };
+		}
+
+		public static SymbolRef Local(string name, int index)
+		{
+			return new SymbolRef() { i_Index = index, i_Type = SymbolRefType.Local, i_Name = name };
+		}
+
+		public static SymbolRef Upvalue(string name, int index)
+		{
+			return new SymbolRef() { i_Index = index, i_Type = SymbolRefType.Upvalue, i_Name = name };
+		}
+		public static SymbolRef Argument(string name, int index)
+		{
+			return new SymbolRef() { i_Index = index, i_Type = SymbolRefType.Argument, i_Name = name };
+		}
+
+		public static SymbolRef Invalid()
+		{
+			return new SymbolRef() { i_Index = -1, i_Type = SymbolRefType.Invalid, i_Name = "!INV!" };
+		}
+
+		public static SymbolRef ObjIndex(DynValue baseObject, DynValue indexObject)
+		{
+			return new SymbolRef() { i_TableRefObject = baseObject, i_TableRefIndex = indexObject, i_Type = SymbolRefType.Index };
+		}
+
+		public bool IsValid()
+		{
+			return i_Type !=  SymbolRefType.Invalid;
+		}
+
+
+		public override string ToString()
+		{
+			return string.Format("{0}[{1}] : {2}", i_Type, i_Index, i_Name);
+		}
+
+
+
+
+	}
+}

+ 1 - 1
src/MoonSharp.Interpreter/Execution/DataTypes/LRefType.cs → src/MoonSharp.Interpreter/Execution/DataTypes/SymbolRefType.cs

@@ -5,7 +5,7 @@ using System.Text;
 
 namespace MoonSharp.Interpreter.Execution
 {
-	public enum LRefType
+	public enum SymbolRefType
 	{
 		Invalid,
 		Global,

+ 11 - 11
src/MoonSharp.Interpreter/Execution/DataTypes/Table.cs

@@ -10,7 +10,7 @@ namespace MoonSharp.Interpreter.Execution
 	public class Table
 	{
 		LinkedList<TablePair> m_Values;
-		LinkedListIndex<RValue, TablePair> m_ValueMap;
+		LinkedListIndex<DynValue, TablePair> m_ValueMap;
 		LinkedListIndex<string, TablePair> m_StringMap;
 		LinkedListIndex<int, TablePair> m_ArrayMap;
 
@@ -21,7 +21,7 @@ namespace MoonSharp.Interpreter.Execution
 			m_Values = new LinkedList<TablePair>();
 			m_StringMap = new LinkedListIndex<string, TablePair>(m_Values);
 			m_ArrayMap = new LinkedListIndex<int, TablePair>(m_Values);
-			m_ValueMap = new LinkedListIndex<RValue, TablePair>(m_Values);
+			m_ValueMap = new LinkedListIndex<DynValue, TablePair>(m_Values);
 		}
 
 		private int GetIntegralKey(double d)
@@ -34,7 +34,7 @@ namespace MoonSharp.Interpreter.Execution
 			return -1;
 		}
 
-		public RValue this[RValue key]
+		public DynValue this[DynValue key]
 		{
 			get 
 			{
@@ -85,15 +85,15 @@ namespace MoonSharp.Interpreter.Execution
 			}
 		}
 
-		private RValue GetValueOrNil(LinkedListNode<TablePair> linkedListNode)
+		private DynValue GetValueOrNil(LinkedListNode<TablePair> linkedListNode)
 		{
 			if (linkedListNode != null)
 				return linkedListNode.Value.Value;
 
-			return RValue.Nil;
+			return DynValue.Nil;
 		}
 
-		public RValue this[string key]
+		public DynValue this[string key]
 		{
 			get
 			{
@@ -101,13 +101,13 @@ namespace MoonSharp.Interpreter.Execution
 			}
 			set
 			{
-				if (m_StringMap.Set(key, new TablePair(new RValue(key), value)))
+				if (m_StringMap.Set(key, new TablePair(DynValue.NewString(key), value)))
 					CollectDeadKeys();
 			}
 		}
 
 
-		public RValue RawGet(string key)
+		public DynValue RawGet(string key)
 		{
 			var linkedListNode = m_StringMap.Find(key);
 
@@ -117,7 +117,7 @@ namespace MoonSharp.Interpreter.Execution
 			return null;
 		}
 
-		public RValue this[int key]
+		public DynValue this[int key]
 		{
 			get
 			{
@@ -125,7 +125,7 @@ namespace MoonSharp.Interpreter.Execution
 			}
 			set
 			{
-				if (m_ArrayMap.Set(key, new TablePair(new RValue(key), value)))
+				if (m_ArrayMap.Set(key, new TablePair(DynValue.NewNumber(key), value)))
 				{
 					CollectDeadKeys();
 					m_CachedLength = -1;
@@ -166,7 +166,7 @@ namespace MoonSharp.Interpreter.Execution
 			return m_Values;
 		}
 
-		public TablePair NextKey(RValue v)
+		public TablePair NextKey(DynValue v)
 		{
 			if (v.Type == DataType.Nil)
 			{

+ 5 - 5
src/MoonSharp.Interpreter/Execution/DataTypes/TablePair.cs

@@ -7,24 +7,24 @@ namespace MoonSharp.Interpreter.Execution.DataTypes
 {
 	public struct TablePair
 	{
-		private static TablePair s_NilNode = new TablePair(RValue.Nil, RValue.Nil);
+		private static TablePair s_NilNode = new TablePair(DynValue.Nil, DynValue.Nil);
 
-		private RValue key, value;
+		private DynValue key, value;
 
-		public RValue Key 
+		public DynValue Key 
 		{
 			get { return key; }
 			private set { Key = key; }
 		}
 
-		public RValue Value
+		public DynValue Value
 		{
 			get { return value; }
 			set { if (key.Type != DataType.Nil) Value = value; }
 		}
 
 
-		public TablePair(RValue key, RValue val) 
+		public TablePair(DynValue key, DynValue val) 
 		{
 			this.key = key;
 			this.value = val;

+ 26 - 0
src/MoonSharp.Interpreter/Execution/FileLoadRequestedEventArgs.cs

@@ -0,0 +1,26 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+
+namespace MoonSharp.Interpreter.Execution
+{
+	public enum FileLoadRequestResponseType
+	{
+		FilePath,
+		ScriptCode,
+		RegisteredModule
+	}
+
+	public class FileLoadRequestedEventArgs : EventArgs 
+	{
+		public string Name { get; internal set; }
+		public bool IsModule { get; internal set; }
+		public Script OriginatingScript { get; internal set; }
+		public DynValue Coroutine { get; internal set; }
+
+		public bool Handled { get; set; }
+		public string Response { get; set; }
+		public FileLoadRequestResponseType ResponseType { get; set; }
+	}
+}

+ 18 - 0
src/MoonSharp.Interpreter/Execution/IExecutionContext.cs

@@ -0,0 +1,18 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using MoonSharp.Interpreter.Execution.VM;
+
+namespace MoonSharp.Interpreter.Execution
+{
+	public interface IExecutionContext
+	{
+		DynValue GetVar(SymbolRef symref);
+		void SetVar(SymbolRef symref, DynValue value);
+		SymbolRef FindVar(string name);
+		DynValue GetMetamethod(DynValue value, string metamethod);
+		DynValue GetMetamethodTailCall(DynValue value, string metamethod, params DynValue[] args);
+		Script GetOwnerScript();
+	}
+}

+ 6 - 6
src/MoonSharp.Interpreter/Execution/Scopes/BuildTimeScope.cs

@@ -41,9 +41,9 @@ namespace MoonSharp.Interpreter.Execution
 		}
 
 
-		public LRef Find(string name)
+		public SymbolRef Find(string name)
 		{
-			LRef local = m_Frames.Last().Find(name);
+			SymbolRef local = m_Frames.Last().Find(name);
 
 			if (local != null)
 				return local;
@@ -58,22 +58,22 @@ namespace MoonSharp.Interpreter.Execution
 				{
 					for (int i = closureLocalBlockIdx; i >= 0; i--)
 					{
-						LRef symb = m_Frames[i].Find(name);
+						SymbolRef symb = m_Frames[i].Find(name);
 						if (symb != null)
 							return closure.CreateUpvalue(this, symb);
 					}
 				}
 			}
 
-			return LRef.Global(name);
+			return SymbolRef.Global(name);
 		}
 
-		public LRef DefineLocal(string name)
+		public SymbolRef DefineLocal(string name)
 		{
 			return m_Frames.Last().DefineLocal(name);
 		}
 
-		public LRef TryDefineLocal(string name)
+		public SymbolRef TryDefineLocal(string name)
 		{
 			return m_Frames.Last().TryDefineLocal(name);
 		}

+ 5 - 5
src/MoonSharp.Interpreter/Execution/Scopes/BuildTimeScopeBlock.cs

@@ -12,7 +12,7 @@ namespace MoonSharp.Interpreter.Execution.Scopes
 
 		internal RuntimeScopeBlock ScopeBlock { get; private set; }
 
-		Dictionary<string, LRef> m_DefinedNames = new Dictionary<string, LRef>();
+		Dictionary<string, SymbolRef> m_DefinedNames = new Dictionary<string, SymbolRef>();
 
 		internal BuildTimeScopeBlock(BuildTimeScopeBlock parent)
 		{
@@ -29,14 +29,14 @@ namespace MoonSharp.Interpreter.Execution.Scopes
 			return block;
 		}
 
-		internal LRef Find(string name)
+		internal SymbolRef Find(string name)
 		{
 			return m_DefinedNames.GetOrDefault(name);
 		}
 
-		internal LRef Define(string name)
+		internal SymbolRef Define(string name)
 		{
-			LRef l = LRef.Local(name, -1);
+			SymbolRef l = SymbolRef.Local(name, -1);
 			m_DefinedNames.Add(name, l);
 			return l;
 		}
@@ -46,7 +46,7 @@ namespace MoonSharp.Interpreter.Execution.Scopes
 			int firstVal = -1;
 			int lastVal = -1;
 
-			foreach (LRef lref in m_DefinedNames.Values)
+			foreach (SymbolRef lref in m_DefinedNames.Values)
 			{
 				int pos = buildTimeScopeFrame.AllocVar(lref);
 

+ 5 - 5
src/MoonSharp.Interpreter/Execution/Scopes/BuildTimeScopeFrame.cs

@@ -43,11 +43,11 @@ namespace MoonSharp.Interpreter.Execution.Scopes
 			return m_ScopeFrame;
 		}
 
-		internal LRef Find(string name)
+		internal SymbolRef Find(string name)
 		{
 			for (var tree = m_ScopeTreeHead; tree != null; tree = tree.Parent)
 			{
-				LRef l = tree.Find(name);
+				SymbolRef l = tree.Find(name);
 
 				if (l != null)
 					return l;
@@ -56,12 +56,12 @@ namespace MoonSharp.Interpreter.Execution.Scopes
 			return null;
 		}
 
-		internal LRef DefineLocal(string name)
+		internal SymbolRef DefineLocal(string name)
 		{
 			return m_ScopeTreeHead.Define(name);
 		}
 
-		internal LRef TryDefineLocal(string name)
+		internal SymbolRef TryDefineLocal(string name)
 		{
 			return m_ScopeTreeHead.Find(name) ?? m_ScopeTreeHead.Define(name);
 		}
@@ -71,7 +71,7 @@ namespace MoonSharp.Interpreter.Execution.Scopes
 			m_ScopeTreeRoot.ResolveLRefs(this);
 		}
 
-		internal int AllocVar(LRef var)
+		internal int AllocVar(SymbolRef var)
 		{
 			var.i_Index = m_ScopeFrame.DebugSymbols.Count;
 			m_ScopeFrame.DebugSymbols.Add(var);

+ 2 - 2
src/MoonSharp.Interpreter/Execution/Scopes/ClosureContext.cs

@@ -5,11 +5,11 @@ using System.Text;
 
 namespace MoonSharp.Interpreter.Execution
 {
-	public class ClosureContext : List<RValue>
+	public class ClosureContext : List<DynValue>
 	{
 		public string[] Symbols { get; private set; }
 
-		internal ClosureContext(LRef[] symbols, IEnumerable<RValue> values)
+		internal ClosureContext(SymbolRef[] symbols, IEnumerable<DynValue> values)
 		{
 			Symbols = symbols.Select(s => s.i_Name).ToArray();
 			this.AddRange(values);

+ 1 - 1
src/MoonSharp.Interpreter/Execution/Scopes/IClosureBuilder.cs

@@ -8,7 +8,7 @@ namespace MoonSharp.Interpreter.Execution
 	public interface IClosureBuilder
 	{
 		object UpvalueCreationTag { get; set; }
-		LRef CreateUpvalue(BuildTimeScope scope, LRef symbol);
+		SymbolRef CreateUpvalue(BuildTimeScope scope, SymbolRef symbol);
 
 	}
 }

+ 1 - 1
src/MoonSharp.Interpreter/Execution/Scopes/LoopTracker.cs

@@ -9,7 +9,7 @@ namespace MoonSharp.Interpreter.Execution
 {
 	interface ILoop
 	{
-		void CompileBreak(Chunk bc);
+		void CompileBreak(ByteCode bc);
 	}
 
 

+ 2 - 2
src/MoonSharp.Interpreter/Execution/Scopes/RuntimeScopeFrame.cs

@@ -7,13 +7,13 @@ namespace MoonSharp.Interpreter.Execution
 {
 	public class RuntimeScopeFrame 
 	{
-		public List<LRef> DebugSymbols { get; private set; }
+		public List<SymbolRef> DebugSymbols { get; private set; }
 		public int Count { get { return DebugSymbols.Count; } }
 		public int ToFirstBlock { get; internal set; }
 
 		public RuntimeScopeFrame()
 		{
-			DebugSymbols = new List<LRef>();
+			DebugSymbols = new List<SymbolRef>();
 		}
 
 		public override string ToString()

+ 183 - 28
src/MoonSharp.Interpreter/Execution/Script.cs

@@ -2,6 +2,7 @@
 using System.Collections.Generic;
 using System.Linq;
 using System.Text;
+using Antlr4.Runtime;
 using MoonSharp.Interpreter.CoreLib;
 using MoonSharp.Interpreter.Debugging;
 using MoonSharp.Interpreter.Diagnostics;
@@ -10,52 +11,206 @@ using MoonSharp.Interpreter.Tree.Statements;
 
 namespace MoonSharp.Interpreter.Execution
 {
+	/// <summary>
+	/// This class implements a Moon# scripting session. Multiple Script objects can coexist in the same program but cannot share
+	/// data among themselves except through the _UNIVERSE table. Data accessed through the _UNIVERSE table is thread safe, so
+	/// Script objects can execute in different threads with no issue, as long as all their callbacks are aware and compatible.
+	/// </summary>
 	public class Script
 	{
-		ChunkStatement m_Script;
-		ScriptLoadingContext m_LoadingContext;
-		Chunk m_GlobalChunk;
-		Processor m_Main;
+		List<Processor> m_Coroutines = new List<Processor>();
+		ByteCode m_ByteCode;
+		Table m_GlobalTable;
+		IDebugger m_Debugger;
 
-		internal Script(ChunkStatement stat, ScriptLoadingContext lcontext)
+		/// <summary>
+		/// Gets the default global table for this script. Unless a different table is intentionally passed (or setfenv has been used)
+		/// execution uses this table.
+		/// </summary>
+		public Table Globals
 		{
-			m_Script = stat;
-			m_LoadingContext = lcontext;
-			Compile();
+			get { return m_GlobalTable; }
 		}
 
-		public void Compile()
+		/// <summary>
+		/// Initializes a new instance of the <see cref="Script"/> class.
+		/// </summary>
+		public Script()
+			: this(ModuleRegister.RegisterCoreModules(new Table(), CoreModules.Preset_Default))
 		{
-			m_GlobalChunk = new Chunk();
-			m_GlobalChunk.Nop("Script start");
-			m_Script.Compile(m_GlobalChunk);
-			m_GlobalChunk.Nop("Script end");
-#if DEBUG
-			m_GlobalChunk.Dump(@"c:\temp\codedump.txt");
-#endif
-			if (m_Main == null)
-				m_Main = new Processor(m_GlobalChunk);
 		}
 
-		public RValue Execute(Table globalContext)
+		/// <summary>
+		/// Initializes a new instance of the <see cref="Script"/> class.
+		/// </summary>
+		/// <param name="coreModules">The core modules to be pre-registered in the default global table.</param>
+		public Script(CoreModules coreModules)
+			: this(ModuleRegister.RegisterCoreModules(new Table(), coreModules))
 		{
-			m_Main.Reset(globalContext ?? new Table());
+		}
 
-			using (var _ = new CodeChrono("MoonSharpScript.Execute"))
-			{
-				return m_Main.InvokeRoot();
-			}
+		/// <summary>
+		/// Initializes a new instance of the <see cref="Script"/> class.
+		/// </summary>
+		/// <param name="globalTable">The default global table.</param>
+		public Script(Table globalTable)
+		{
+			m_ByteCode = new ByteCode();
+			m_GlobalTable = globalTable;
+			m_Coroutines.Add(new Processor(this, m_GlobalTable, m_ByteCode));
+		}
+
+
+		/// <summary>
+		/// Loads a string containing a Lua/Moon# script.
+		/// </summary>
+		/// <param name="code">The code.</param>
+		/// <param name="globalTable">The global table to bind to this chunk.</param>
+		/// <returns>A DynValue containing a function which will execute the loaded code.</returns>
+		public DynValue LoadString(string code, Table globalTable = null)
+		{
+			int address = ChunkStatement.LoadFromICharStream(new AntlrInputStream(code), 
+				string.Format("<string:{0:X8}>", code.GetHashCode()),
+				m_ByteCode);
+
+			return MakeClosure(address, globalTable);
+		}
+
+		/// <summary>
+		/// Loads a string containing a Lua/Moon# script.
+		/// </summary>
+		/// <param name="filename">The code.</param>
+		/// <param name="globalContext">The global table to bind to this chunk.</param>
+		/// <returns>A DynValue containing a function which will execute the loaded code.</returns>
+		public DynValue LoadFile(string filename, Table globalContext = null)
+		{
+			int address = ChunkStatement.LoadFromICharStream(new AntlrFileStream(filename), filename, m_ByteCode);
+			return MakeClosure(address, globalContext);
+		}
+
+		/// <summary>
+		/// Loads and executes a string containing a Lua/Moon# script.
+		/// </summary>
+		/// <param name="code">The code.</param>
+		/// <param name="globalContext">The global context.</param>
+		/// <param name="coroutine">The coroutine index, or -1 to use the first free (or current) coroutine index.</param>
+		/// <returns>
+		/// A DynValue containing the result of the processing of the loaded chunk.
+		/// </returns>
+		public DynValue DoString(string code, Table globalContext = null, int coroutine = -1)
+		{
+			coroutine = FixCoroutineIndex(coroutine);
+
+			DynValue func = LoadString(code, globalContext);
+			return Call(coroutine, func);
+		}
+
+		/// <summary>
+		/// Loads and executes a file containing a Lua/Moon# script.
+		/// </summary>
+		/// <param name="filename">The filename.</param>
+		/// <param name="globalContext">The global context.</param>
+		/// <param name="coroutine">The coroutine index, or -1 to use the first free (or current) coroutine index.</param>
+		/// <returns>
+		/// A DynValue containing the result of the processing of the loaded chunk.
+		/// </returns>
+		public DynValue DoFile(string filename, Table globalContext = null, int coroutine = -1)
+		{
+			coroutine = FixCoroutineIndex(coroutine);
+
+			DynValue func = LoadFile(filename, globalContext);
+			return Call(coroutine, func);
 		}
 
 
-		public void AttachDebugger(IDebugger debugger)
+		/// <summary>
+		/// Runs the specified file with all possible defaults for quick experimenting.
+		/// </summary>
+		/// <param name="filename">The filename.</param>
+		/// A DynValue containing the result of the processing of the executed script.
+		public static DynValue RunFile(string filename)
 		{
-			if (debugger != null)
-				debugger.SetSourceCode(m_GlobalChunk, null);
+			Script S = new Script();
+			return S.DoFile(filename);
+		}
+
+		/// <summary>
+		/// Runs the specified code with all possible defaults for quick experimenting.
+		/// </summary>
+		/// <param name="code">The Lua/Moon# code.</param>
+		/// A DynValue containing the result of the processing of the executed script.
+		public static DynValue RunString(string code)
+		{
+			Script S = new Script();
+			return S.DoString(code);
+		}
+
+		/// <summary>
+		/// Creates a closure from a bytecode address.
+		/// </summary>
+		/// <param name="address">The address.</param>
+		/// <param name="globalContext">The global context.</param>
+		/// <returns></returns>
+		private DynValue MakeClosure(int address, Table globalContext)
+		{
+			Closure c = new Closure(address, new SymbolRef[0], new DynValue[0]);
+			c.GlobalEnv = globalContext;
+			return DynValue.NewClosure(c);
+		}
+		/// <summary>
+		/// Fixes the index of a coroutine translating a -1 parameter.
+		/// </summary>
+		/// <param name="coroutine">The coroutine.</param>
+		private int FixCoroutineIndex(int coroutine)
+		{
+			return (coroutine >= 0) ? coroutine : 0;
+		}
+
+		/// <summary>
+		/// Calls the specified function.
+		/// </summary>
+		/// <param name="coroutine">The coroutine on which to execute, or -1 to use the first-free (or current) coroutine.</param>
+		/// <param name="function">The Lua/Moon# function to be called - callbacks are not supported.</param>
+		/// <param name="args">The arguments to pass to the function.</param>
+		/// <returns></returns>
+		public DynValue Call(int coroutine, DynValue function, params DynValue[] args)
+		{
+			return m_Coroutines[coroutine].Call(function, args);
+		}
 
-			m_Main.AttachDebugger(debugger);
+		/// <summary>
+		/// Gets the main chunk function.
+		/// </summary>
+		/// <param name="globalContext">The global context.</param>
+		/// <returns>A DynValue containing a function which executes the first chunk that has been loaded.</returns>
+		public DynValue GetMainChunk(Table globalContext = null)
+		{
+			return MakeClosure(0, globalContext);
 		}
 
+		/// <summary>
+		/// Attaches a debugger.
+		/// </summary>
+		/// <param name="debugger">The debugger object.</param>
+		/// <param name="coroutine">
+		/// The coroutine to which the debugger attaches, or -1 to attach it to all coroutines. 
+		/// If -1 is specified, the debugger is also automatically attached to new coroutines.
+		/// </param>
+		public void AttachDebugger(IDebugger debugger, int coroutine = -1)
+		{
+			if (coroutine < 0)
+			{
+				m_Debugger = debugger;
+				foreach (var C in m_Coroutines)
+					C.AttachDebugger(debugger);
+			}
+			else
+			{
+				m_Coroutines[coroutine].AttachDebugger(debugger);
+			}
+
+			m_Debugger.SetSourceCode(m_ByteCode, null);
+		}
 
 	}
 }

+ 12 - 7
src/MoonSharp.Interpreter/Execution/VM/Chunk.cs → src/MoonSharp.Interpreter/Execution/VM/ByteCode.cs

@@ -10,7 +10,7 @@ using System.Threading;
 
 namespace MoonSharp.Interpreter.Execution.VM
 {
-	public class Chunk
+	public class ByteCode
 	{
 		public List<Instruction> Code = new List<Instruction>();
 		internal LoopTracker LoopTracker = new LoopTracker();
@@ -73,12 +73,12 @@ namespace MoonSharp.Interpreter.Execution.VM
 			Emit(new Instruction() { OpCode = OpCode.TailChk });
 		}
 
-		public Instruction Load(LRef symref)
+		public Instruction Load(SymbolRef symref)
 		{
 			return Emit(new Instruction() { OpCode = OpCode.Load, Symbol = symref });
 		}
 
-		public Instruction Literal(RValue value)
+		public Instruction Literal(DynValue value)
 		{
 			return Emit(new Instruction() { OpCode = OpCode.Literal, Value = value });
 		}
@@ -93,7 +93,7 @@ namespace MoonSharp.Interpreter.Execution.VM
 			return Emit(new Instruction() { OpCode = OpCode.Store });
 		}
 
-		public Instruction Symbol(LRef symref)
+		public Instruction Symbol(SymbolRef symref)
 		{
 			return Emit(new Instruction() { OpCode = OpCode.Symbol, Symbol = symref });
 		}
@@ -147,12 +147,12 @@ namespace MoonSharp.Interpreter.Execution.VM
 			return Emit(new Instruction() { OpCode = OpCode.Exit, Block = runtimeScopeBlock });
 		}
 
-		public Instruction Closure(LRef[] symbols, int jmpnum)
+		public Instruction Closure(SymbolRef[] symbols, int jmpnum)
 		{
 			return Emit(new Instruction() { OpCode = OpCode.Closure, SymbolList = symbols, NumVal = jmpnum });
 		}
 
-		public Instruction Args(LRef[] symbols)
+		public Instruction Args(SymbolRef[] symbols)
 		{
 			return Emit(new Instruction() { OpCode = OpCode.Args, SymbolList = symbols });
 		}
@@ -167,7 +167,7 @@ namespace MoonSharp.Interpreter.Execution.VM
 			return Emit(new Instruction() { OpCode = OpCode.ToNum });
 		}
 
-		public Instruction SymStorN(LRef symb)
+		public Instruction SymStorN(SymbolRef symb)
 		{
 			return Emit(new Instruction() { OpCode = OpCode.SymStorN, Symbol = symb });
 		}
@@ -226,5 +226,10 @@ namespace MoonSharp.Interpreter.Execution.VM
 				Name = funcName 
 			});
 		}
+
+		public Instruction Scalar()
+		{
+			return Emit(new Instruction() { OpCode = OpCode.Scalar });
+		}
 	}
 }

+ 2 - 2
src/MoonSharp.Interpreter/Execution/VM/CallStackItem.cs

@@ -8,11 +8,11 @@ namespace MoonSharp.Interpreter.Execution.VM
 	public class CallStackItem
 	{
 		public int Debug_EntryPoint;
-		public LRef[] Debug_Symbols;
+		public SymbolRef[] Debug_Symbols;
 
 		public int BasePointer;
 		public int ReturnAddress;
-		public RValue[] LocalScope;
+		public DynValue[] LocalScope;
 		public ClosureContext ClosureScope;
 	}
 

+ 4 - 4
src/MoonSharp.Interpreter/Execution/VM/Instruction.cs

@@ -8,10 +8,10 @@ namespace MoonSharp.Interpreter.Execution.VM
 	public class Instruction
 	{
 		public OpCode OpCode;
-		public LRef Symbol;
-		public LRef[] SymbolList;
+		public SymbolRef Symbol;
+		public SymbolRef[] SymbolList;
 		public string Name;
-		public RValue Value;
+		public DynValue Value;
 		public int NumVal;
 		public int NumVal2;
 		public RuntimeScopeBlock Block;
@@ -87,7 +87,7 @@ namespace MoonSharp.Interpreter.Execution.VM
 				return frame.ToString();
 		}
 
-		private string PurifyFromNewLines(RValue Value)
+		private string PurifyFromNewLines(DynValue Value)
 		{
 			return Value.ToString().Replace('\n', ' ').Replace('\r', ' ');
 		}

+ 1 - 0
src/MoonSharp.Interpreter/Execution/VM/OpCode.cs

@@ -58,6 +58,7 @@ namespace MoonSharp.Interpreter.Execution.VM
 
 		// Type conversions and manipulations
 		MkTuple,	// Creates a tuple from the topmost n values
+		Scalar,		// Converts the topmost tuple to a scalar
 		Incr,		// Performs an add operation, without extracting the operands from the v-stack and assuming the operands are numbers.
 		ToNum,		// Converts the top of the stack to a number
 		ToBool,		// Converts the top of the stack to a boolean

+ 20 - 17
src/MoonSharp.Interpreter/Execution/VM/Processor/Processor.cs

@@ -9,41 +9,44 @@ namespace MoonSharp.Interpreter.Execution.VM
 {
 	sealed partial class Processor
 	{
-		Chunk m_RootChunk;
-		Chunk m_CurChunk;
+		ByteCode m_RootChunk;
 
-		FastStack<RValue> m_ValueStack = new FastStack<RValue>(131072);
+		FastStack<DynValue> m_ValueStack = new FastStack<DynValue>(131072);
 		FastStack<CallStackItem> m_ExecutionStack = new FastStack<CallStackItem>(131072);
+		Table m_GlobalTable;
 
 		IDebugger m_DebuggerAttached = null;
 		DebuggerAction.ActionType m_DebuggerCurrentAction = DebuggerAction.ActionType.None;
 		int m_DebuggerCurrentActionTarget = -1;
+		Script m_Script;
 
-		Table m_GlobalTable = new Table();
-
-		public Processor(Chunk rootChunk)
+		public Processor(Script script, Table globalContext, ByteCode byteCode)
 		{
-			m_RootChunk = m_CurChunk = rootChunk;
+			m_RootChunk = byteCode;
+			m_GlobalTable = globalContext;
+			m_Script = script;
 		}
 
-		public void Reset(Table global)
-		{
-			m_CurChunk = m_RootChunk;
-			m_GlobalTable = global;
-		}
 
-		public RValue InvokeRoot()
+		public DynValue Call(DynValue function, DynValue[] args)
 		{
-			m_ValueStack.Push(new RValue(0));  // func val
-			m_ValueStack.Push(new RValue(0));  // func args count
+			m_ValueStack.Push(function);  // func val
+
+			args = Internal_AdjustTuple(args);
+
+			for (int i = 0; i < args.Length; i++)
+				m_ValueStack.Push(args[i]);
+			
+			m_ValueStack.Push(DynValue.NewNumber(args.Length));  // func args count
+
 			m_ExecutionStack.Push(new CallStackItem()
 			{
 				BasePointer = m_ValueStack.Count,
-				Debug_EntryPoint = 0,
+				Debug_EntryPoint = function.Function.ByteCodeLocation,
 				ReturnAddress = -1,
 			});
 
-			return Processing_Loop(0);
+			return Processing_Loop(function.Function.ByteCodeLocation);
 		}
 	}
 }

+ 4 - 4
src/MoonSharp.Interpreter/Execution/VM/Processor/Processor_Debugger.cs

@@ -52,7 +52,7 @@ namespace MoonSharp.Interpreter.Execution.VM
 						m_DebuggerCurrentActionTarget = -1;
 						return;
 					case DebuggerAction.ActionType.ToggleBreakpoint:
-						m_CurChunk.Code[action.InstructionPtr].Breakpoint = !m_CurChunk.Code[action.InstructionPtr].Breakpoint;
+						m_RootChunk.Code[action.InstructionPtr].Breakpoint = !m_RootChunk.Code[action.InstructionPtr].Breakpoint;
 						break;
 					case DebuggerAction.ActionType.Refresh:
 						RefreshDebugger();
@@ -97,11 +97,11 @@ namespace MoonSharp.Interpreter.Execution.VM
 
 		private WatchItem Debugger_RefreshWatch(string name)
 		{
-			LRef L = FindRefByName(name);
+			SymbolRef L = FindRefByName(name);
 
 			if (L != null)
 			{
-				RValue v = this.GetGenericSymbol(L);
+				DynValue v = this.GetGenericSymbol(L);
 
 				return new WatchItem()
 				{
@@ -124,7 +124,7 @@ namespace MoonSharp.Interpreter.Execution.VM
 			{
 				var c = m_ExecutionStack.Peek(i);
 
-				var I = m_CurChunk.Code[c.Debug_EntryPoint];
+				var I = m_RootChunk.Code[c.Debug_EntryPoint];
 
 				string callname = I.OpCode == OpCode.BeginFn ? I.Name : null;
 

+ 13 - 7
src/MoonSharp.Interpreter/Execution/VM/Processor/Processor_IExecutionContext.cs

@@ -7,22 +7,22 @@ namespace MoonSharp.Interpreter.Execution.VM
 {
 	sealed partial class Processor : IExecutionContext
 	{
-		RValue IExecutionContext.GetVar(LRef symref)
+		DynValue IExecutionContext.GetVar(SymbolRef symref)
 		{
 			return this.GetGenericSymbol(symref);
 		}
 
-		void IExecutionContext.SetVar(LRef symref, RValue value)
+		void IExecutionContext.SetVar(SymbolRef symref, DynValue value)
 		{
 			AssignGenericSymbol(symref, value);
 		}
 
-		LRef IExecutionContext.FindVar(string name)
+		SymbolRef IExecutionContext.FindVar(string name)
 		{
 			return FindRefByName(name);
 		}
 
-		RValue IExecutionContext.GetMetamethod(RValue value, string metamethod)
+		DynValue IExecutionContext.GetMetamethod(DynValue value, string metamethod)
 		{
 			if (value.Meta == null || value.Type == DataType.Nil)
 				return null;
@@ -38,13 +38,19 @@ namespace MoonSharp.Interpreter.Execution.VM
 			return metameth;
 		}
 
-		RValue IExecutionContext.GetMetamethodTailCall(RValue value, string metamethod, params RValue[] args)
+		DynValue IExecutionContext.GetMetamethodTailCall(DynValue value, string metamethod, params DynValue[] args)
 		{
-			RValue meta = ((IExecutionContext)this).GetMetamethod(value, metamethod);
+			DynValue meta = ((IExecutionContext)this).GetMetamethod(value, metamethod);
 
 			if (meta == null) return null;
 
-			return new RValue(meta, args);
+			return DynValue.NewTailCallReq(meta, args);
+		}
+
+
+		Script IExecutionContext.GetOwnerScript()
+		{
+			return m_Script;
 		}
 	}
 }

+ 117 - 141
src/MoonSharp.Interpreter/Execution/VM/Processor/Processor_InstructionLoop.cs

@@ -9,11 +9,11 @@ namespace MoonSharp.Interpreter.Execution.VM
 {
 	sealed partial class Processor
 	{
-		private RValue Processing_Loop(int instructionPtr)
+		private DynValue Processing_Loop(int instructionPtr)
 		{
 			while (true)
 			{
-				Instruction i = m_CurChunk.Code[instructionPtr];
+				Instruction i = m_RootChunk.Code[instructionPtr];
 
 				if (m_DebuggerAttached != null)
 				{
@@ -78,6 +78,9 @@ namespace MoonSharp.Interpreter.Execution.VM
 					case OpCode.TailChk:
 						instructionPtr = ExecTailChk(i, instructionPtr);
 						break;
+					case OpCode.Scalar:
+						m_ValueStack.Push(m_ValueStack.Pop().ToScalar());
+						break;
 					case OpCode.Not:
 						ExecNot(i);
 						break;
@@ -87,7 +90,7 @@ namespace MoonSharp.Interpreter.Execution.VM
 						break;
 					case OpCode.JNil:
 						{
-							RValue v = m_ValueStack.Pop();
+							DynValue v = m_ValueStack.Pop();
 
 							if (v.Type == DataType.Nil)
 								instructionPtr = i.NumVal;
@@ -100,7 +103,7 @@ namespace MoonSharp.Interpreter.Execution.VM
 						ExecStore(i);
 						break;
 					case OpCode.Symbol:
-						m_ValueStack.Push(new RValue(i.Symbol));
+						m_ValueStack.Push(DynValue.NewReference(i.Symbol));
 						break;
 					case OpCode.Assign:
 						ExecAssign(i);
@@ -119,13 +122,13 @@ namespace MoonSharp.Interpreter.Execution.VM
 						ClearBlockData(i.Block, i.OpCode == OpCode.Exit);
 						break;
 					case OpCode.Closure:
-						m_ValueStack.Push(new RValue(new Closure(i.NumVal, i.SymbolList, m_ExecutionStack.Peek().LocalScope)));
+						m_ValueStack.Push(DynValue.NewClosure(new Closure(i.NumVal, i.SymbolList, m_ExecutionStack.Peek().LocalScope)));
 						break;
 					case OpCode.BeginFn:
 						ExecBeginFn(i);
 						break;
 					case OpCode.ToBool:
-						m_ValueStack.Push(m_ValueStack.Pop().AsBoolean());
+						m_ValueStack.Push(DynValue.NewBoolean(m_ValueStack.Pop().CastToBool()));
 						break;
 					case OpCode.Args:
 						ExecArgs(i);
@@ -160,7 +163,7 @@ namespace MoonSharp.Interpreter.Execution.VM
 						ExecIndexRef(i, true);
 						break;
 					case OpCode.NewTable:
-						m_ValueStack.Push(new RValue(new Table()));
+						m_ValueStack.Push(DynValue.NewTable(new Table()));
 						break;
 					case OpCode.IterPrep:
 						ExecIterPrep(i);
@@ -183,7 +186,7 @@ namespace MoonSharp.Interpreter.Execution.VM
 			if (m_ValueStack.Count == 1)
 				return m_ValueStack.Pop();
 			else if (m_ValueStack.Count == 0)
-				return RValue.Nil;
+				return DynValue.Nil;
 			else
 				throw new InternalErrorException("Unexpected value stack count at program end : {0}", m_ValueStack.Count);
 
@@ -191,30 +194,18 @@ namespace MoonSharp.Interpreter.Execution.VM
 
 		private void ExecMkTuple(Instruction i)
 		{
-			//RValue[] t = new RValue[i.NumVal];
-			//for(int ii = i.NumVal - 1; ii >= 0; ii--)
-			//{
-			//	if (ii == i.NumVal - 1)
-			//	{
-			//		t[ii] = m_ValueStack.Pop();
-			//	}
-			//	else
-			//	{
-			//		t[ii] = m_ValueStack.Pop().ToSimplestValue();
-			//	}
-			//}
-
-
-			var explist = StackTopToArrayReverse(i.NumVal, true);
-			var v = RValue.FromPotentiallyNestedTuple(explist);
-			m_ValueStack.Push(v);
+			Slice<DynValue> slice = new Slice<DynValue>(m_ValueStack, m_ValueStack.Count - i.NumVal, i.NumVal, false);
+
+			var v = Internal_AdjustTuple(slice);
+
+			m_ValueStack.Push(DynValue.NewTuple(v));
 		}
 
 		private void ExecToNum(Instruction i)
 		{
-			double? v = m_ValueStack.Pop().AsNumber();
+			double? v = m_ValueStack.Pop().CastToNumber();
 			if (v.HasValue)
-				m_ValueStack.Push(new RValue(v.Value));
+				m_ValueStack.Push(DynValue.NewNumber(v.Value));
 			else
 				throw new ScriptRuntimeException(null, "Can't convert value to number");
 		}
@@ -222,14 +213,14 @@ namespace MoonSharp.Interpreter.Execution.VM
 
 		private void ExecIterUpd(Instruction i)
 		{
-			RValue v = m_ValueStack.Peek(0);
-			RValue t = m_ValueStack.Peek(1);
+			DynValue v = m_ValueStack.Peek(0);
+			DynValue t = m_ValueStack.Peek(1);
 			t.Tuple[2] = v;
 		}
 
 		private void ExecExpTuple(Instruction i)
 		{
-			RValue t = m_ValueStack.Peek(i.NumVal);
+			DynValue t = m_ValueStack.Peek(i.NumVal);
 
 			if (t.Type == DataType.Tuple)
 			{
@@ -245,23 +236,23 @@ namespace MoonSharp.Interpreter.Execution.VM
 
 		private void ExecIterPrep(Instruction i)
 		{
-			RValue v = m_ValueStack.Pop();
+			DynValue v = m_ValueStack.Pop();
 
 			if (v.Type != DataType.Tuple)
 			{
-				v = new RValue(new RValue[] { v, RValue.Nil, RValue.Nil });
+				v = DynValue.NewTuple(v, DynValue.Nil, DynValue.Nil);
 			}
 			else if (v.Tuple.Length > 3)
 			{
-				v = new RValue(new RValue[] { v.Tuple[0], v.Tuple[1], v.Tuple[2] });
+				v = DynValue.NewTuple(v.Tuple[0], v.Tuple[1], v.Tuple[2]);
 			}
 			else if (v.Tuple.Length == 2)
 			{
-				v = new RValue(new RValue[] { v.Tuple[0], v.Tuple[1], RValue.Nil });
+				v = DynValue.NewTuple(v.Tuple[0], v.Tuple[1], DynValue.Nil);
 			}
 			else if (v.Tuple.Length == 1)
 			{
-				v = new RValue(new RValue[] { v.Tuple[0], RValue.Nil, RValue.Nil });
+				v = DynValue.NewTuple(v.Tuple[0], DynValue.Nil, DynValue.Nil);
 			}
 
 			m_ValueStack.Push(v);
@@ -286,8 +277,8 @@ namespace MoonSharp.Interpreter.Execution.VM
 
 		private void ExecIncr(Instruction i)
 		{
-			RValue top = m_ValueStack.Peek(0);
-			RValue btm = m_ValueStack.Peek(i.NumVal);
+			DynValue top = m_ValueStack.Peek(0);
+			DynValue btm = m_ValueStack.Peek(i.NumVal);
 
 			if (top.ReadOnly)
 			{
@@ -303,8 +294,8 @@ namespace MoonSharp.Interpreter.Execution.VM
 
 		private void ExecNot(Instruction i)
 		{
-			RValue v = m_ValueStack.Pop();
-			m_ValueStack.Push(new RValue(!(v.TestAsBoolean())));
+			DynValue v = m_ValueStack.Pop();
+			m_ValueStack.Push(DynValue.NewBoolean(!(v.CastToBool())));
 		}
 
 
@@ -315,7 +306,7 @@ namespace MoonSharp.Interpreter.Execution.VM
 				int retpoint = PopToBasePointer();
 				var argscnt = (int)(m_ValueStack.Pop().Number);
 				m_ValueStack.RemoveLast(argscnt + 1);
-				m_ValueStack.Push(RValue.Nil);
+				m_ValueStack.Push(DynValue.Nil);
 				return retpoint;
 			}
 			else if (i.NumVal == 1)
@@ -337,13 +328,13 @@ namespace MoonSharp.Interpreter.Execution.VM
 		{
 			CallStackItem c = m_ExecutionStack.Peek();
 			c.Debug_Symbols = i.SymbolList;
-			c.LocalScope = new RValue[i.NumVal];
+			c.LocalScope = new DynValue[i.NumVal];
 
 			if (i.NumVal2 >= 0 && i.NumVal > 0)
 			{
 				for (int idx = 0; idx < i.NumVal2; idx++)
 				{
-					c.LocalScope[idx] = new RValue();
+					c.LocalScope[idx] = DynValue.NewNil();
 				}
 			}
 		}
@@ -372,7 +363,7 @@ namespace MoonSharp.Interpreter.Execution.VM
 			{
 				if (i >= numargs)
 				{
-					this.AssignGenericSymbol(I.SymbolList[i], new RValue());
+					this.AssignGenericSymbol(I.SymbolList[i], DynValue.NewNil());
 				}
 				else
 				{
@@ -384,11 +375,11 @@ namespace MoonSharp.Interpreter.Execution.VM
 
 		private int Internal_ExecCall(int argsCount, int instructionPtr)
 		{
-			RValue fn = m_ValueStack.Peek(argsCount);
+			DynValue fn = m_ValueStack.Peek(argsCount);
 
 			if (fn.Type == DataType.ClrFunction)
 			{
-				IList<RValue> args = new Slice<RValue>(m_ValueStack, m_ValueStack.Count - argsCount, argsCount, false);
+				IList<DynValue> args = new Slice<DynValue>(m_ValueStack, m_ValueStack.Count - argsCount, argsCount, false);
 				var ret = fn.Callback.Invoke(this, args);
 				m_ValueStack.RemoveLast(argsCount + 1);
 				m_ValueStack.Push(ret);
@@ -396,7 +387,7 @@ namespace MoonSharp.Interpreter.Execution.VM
 			}
 			else if (fn.Type == DataType.Function)
 			{
-				m_ValueStack.Push(new RValue(argsCount));
+				m_ValueStack.Push(DynValue.NewNumber(argsCount));
 				m_ExecutionStack.Push(new CallStackItem()
 				{
 					BasePointer = m_ValueStack.Count,
@@ -414,7 +405,7 @@ namespace MoonSharp.Interpreter.Execution.VM
 
 					if (m != null && m.Type != DataType.Nil)
 					{
-						RValue[] tmp = new RValue[argsCount + 1];
+						DynValue[] tmp = new DynValue[argsCount + 1];
 						for (int i = 0; i < argsCount + 1; i++)
 							tmp[i] = m_ValueStack.Pop();
 
@@ -435,7 +426,7 @@ namespace MoonSharp.Interpreter.Execution.VM
 
 		private int ExecTailChk(Instruction i, int instructionPtr)
 		{
-			RValue tail = m_ValueStack.Peek(0);
+			DynValue tail = m_ValueStack.Peek(0);
 
 			if (tail.Type == DataType.TailCallRequest)
 			{
@@ -458,9 +449,9 @@ namespace MoonSharp.Interpreter.Execution.VM
 
 		private int JumpBool(Instruction i, bool expectedValueForJump, int instructionPtr)
 		{
-			RValue op = m_ValueStack.Pop();
+			DynValue op = m_ValueStack.Pop();
 
-			if (op.TestAsBoolean() == expectedValueForJump)
+			if (op.CastToBool() == expectedValueForJump)
 				return i.NumVal;
 
 			return instructionPtr;
@@ -470,9 +461,9 @@ namespace MoonSharp.Interpreter.Execution.VM
 		{
 			bool expectedValToShortCircuit = i.OpCode == OpCode.JtOrPop;
 
-			RValue op = m_ValueStack.Peek();
+			DynValue op = m_ValueStack.Peek();
 
-			if (op.TestAsBoolean() == expectedValToShortCircuit)
+			if (op.CastToBool() == expectedValToShortCircuit)
 			{
 				return i.NumVal;
 			}
@@ -483,29 +474,19 @@ namespace MoonSharp.Interpreter.Execution.VM
 			}
 		}
 
-		private void Bool(Instruction i)
+		private void Internal_Assign(SymbolRef l, DynValue r)
 		{
-			RValue v = m_ValueStack.Peek();
-			if (v.Type != DataType.Boolean)
-			{
-				m_ValueStack.Pop();
-				m_ValueStack.Push(v.ToSimplestValue().AsBoolean());
-			}
-		}
-
-		private void Internal_Assign(LRef l, RValue r)
-		{
-			if (l.i_Type == LRefType.Index)
+			if (l.i_Type == SymbolRefType.Index)
 			{
 				l.i_TableRefObject.Table[l.i_TableRefIndex] = r;
 			}
 			else
 			{
-				this.AssignGenericSymbol(l, r.ToSimplestValue());
+				this.AssignGenericSymbol(l, r.ToScalar());
 			}
 		}
 
-		private void Internal_Assign(RValue l, RValue r)
+		private void Internal_Assign(DynValue l, DynValue r)
 		{
 			if (l.Type == DataType.Symbol)
 			{
@@ -519,8 +500,8 @@ namespace MoonSharp.Interpreter.Execution.VM
 
 		private void ExecIndexGet(Instruction i, bool methodCall)
 		{
-			RValue indexValue = m_ValueStack.Pop();
-			RValue baseValue = m_ValueStack.Pop();
+			DynValue indexValue = m_ValueStack.Pop();
+			DynValue baseValue = m_ValueStack.Pop();
 
 			if (baseValue.Type != DataType.Table)
 			{
@@ -528,7 +509,7 @@ namespace MoonSharp.Interpreter.Execution.VM
 			}
 			else
 			{
-				RValue v = baseValue.Table[indexValue];
+				DynValue v = baseValue.Table[indexValue];
 				m_ValueStack.Push(v.AsReadOnly());
 			}
 
@@ -538,8 +519,8 @@ namespace MoonSharp.Interpreter.Execution.VM
 
 		private void ExecIndexRef(Instruction i, bool keepOnStack)
 		{
-			RValue indexValue = m_ValueStack.Pop();
-			RValue baseValue = keepOnStack ? m_ValueStack.Peek() : m_ValueStack.Pop();
+			DynValue indexValue = m_ValueStack.Pop();
+			DynValue baseValue = keepOnStack ? m_ValueStack.Peek() : m_ValueStack.Pop();
 
 			if (baseValue.Type != DataType.Table)
 			{
@@ -547,15 +528,15 @@ namespace MoonSharp.Interpreter.Execution.VM
 			}
 			else
 			{
-				LRef s = LRef.ObjIndex(baseValue, indexValue);
-				m_ValueStack.Push(new RValue(s));
+				SymbolRef s = SymbolRef.ObjIndex(baseValue, indexValue);
+				m_ValueStack.Push(DynValue.NewReference(s));
 			}
 		}
 
 		private void ExecStore(Instruction i)
 		{
-			RValue r = m_ValueStack.Pop();
-			RValue l = m_ValueStack.Pop();
+			DynValue r = m_ValueStack.Pop();
+			DynValue l = m_ValueStack.Pop();
 
 			Internal_Assign(l, r);
 		}
@@ -569,15 +550,15 @@ namespace MoonSharp.Interpreter.Execution.VM
 
 		private void ExecAssign(Instruction i)
 		{
-			Slice<RValue> rvalues = new Slice<RValue>(m_ValueStack, m_ValueStack.Count - i.NumVal2, i.NumVal2, false);
-			Slice<RValue> lvalues = new Slice<RValue>(m_ValueStack, m_ValueStack.Count - i.NumVal2 - i.NumVal, i.NumVal, false);
+			Slice<DynValue> rvalues = new Slice<DynValue>(m_ValueStack, m_ValueStack.Count - i.NumVal2, i.NumVal2, false);
+			Slice<DynValue> lvalues = new Slice<DynValue>(m_ValueStack, m_ValueStack.Count - i.NumVal2 - i.NumVal, i.NumVal, false);
 
 			Internal_MultiAssign(lvalues, rvalues);
 
 			m_ValueStack.CropAtCount(m_ValueStack.Count - i.NumVal - i.NumVal2);
 		}
 
-		private void Internal_MultiAssign(Slice<RValue> lValues, Slice<RValue> rValues)
+		private void Internal_MultiAssign(Slice<DynValue> lValues, Slice<DynValue> rValues)
 		{
 			int li = 0;
 			int rValues_Count = rValues.Count;
@@ -585,17 +566,17 @@ namespace MoonSharp.Interpreter.Execution.VM
 
 			for (int ri = 0; ri < rValues_Count && li < lValues_Count; ri++, li++)
 			{
-				RValue vv = rValues[ri];
+				DynValue vv = rValues[ri];
 
 				if ((ri != rValues_Count - 1) || (vv.Type != DataType.Tuple))
 				{
-					Internal_Assign(lValues[li], vv.ToSingleValue());
+					Internal_Assign(lValues[li], vv.ToScalar());
 				}
 				else
 				{
 					for (int rri = 0, len = vv.Tuple.Length; rri < len && li < lValues_Count; rri++, li++)
 					{
-						Internal_Assign(lValues[li], vv.Tuple[rri].ToSingleValue());
+						Internal_Assign(lValues[li], vv.Tuple[rri].ToScalar());
 					}
 				}
 			}
@@ -612,15 +593,15 @@ namespace MoonSharp.Interpreter.Execution.VM
 
 		private int ExecAdd(Instruction i, int instructionPtr)
 		{
-			RValue r = m_ValueStack.Pop();
-			RValue l = m_ValueStack.Pop();
+			DynValue r = m_ValueStack.Pop();
+			DynValue l = m_ValueStack.Pop();
 
-			double? rn = r.AsNumber();
-			double? ln = l.AsNumber();
+			double? rn = r.CastToNumber();
+			double? ln = l.CastToNumber();
 
 			if (ln.HasValue && rn.HasValue)
 			{
-				m_ValueStack.Push(new RValue(ln.Value + rn.Value));
+				m_ValueStack.Push(DynValue.NewNumber(ln.Value + rn.Value));
 				return instructionPtr;
 			}
 			else 
@@ -633,15 +614,15 @@ namespace MoonSharp.Interpreter.Execution.VM
 
 		private int ExecSub(Instruction i, int instructionPtr)
 		{
-			RValue r = m_ValueStack.Pop();
-			RValue l = m_ValueStack.Pop();
+			DynValue r = m_ValueStack.Pop();
+			DynValue l = m_ValueStack.Pop();
 
-			double? rn = r.AsNumber();
-			double? ln = l.AsNumber();
+			double? rn = r.CastToNumber();
+			double? ln = l.CastToNumber();
 
 			if (ln.HasValue && rn.HasValue)
 			{
-				m_ValueStack.Push(new RValue(ln.Value - rn.Value));
+				m_ValueStack.Push(DynValue.NewNumber(ln.Value - rn.Value));
 				return instructionPtr;
 			}
 			else
@@ -655,15 +636,15 @@ namespace MoonSharp.Interpreter.Execution.VM
 
 		private int ExecMul(Instruction i, int instructionPtr)
 		{
-			RValue r = m_ValueStack.Pop();
-			RValue l = m_ValueStack.Pop();
+			DynValue r = m_ValueStack.Pop();
+			DynValue l = m_ValueStack.Pop();
 
-			double? rn = r.AsNumber();
-			double? ln = l.AsNumber();
+			double? rn = r.CastToNumber();
+			double? ln = l.CastToNumber();
 
 			if (ln.HasValue && rn.HasValue)
 			{
-				m_ValueStack.Push(new RValue(ln.Value * rn.Value));
+				m_ValueStack.Push(DynValue.NewNumber(ln.Value * rn.Value));
 				return instructionPtr;
 			}
 			else
@@ -676,15 +657,15 @@ namespace MoonSharp.Interpreter.Execution.VM
 		
 		private int ExecMod(Instruction i, int instructionPtr)
 		{
-			RValue r = m_ValueStack.Pop();
-			RValue l = m_ValueStack.Pop();
+			DynValue r = m_ValueStack.Pop();
+			DynValue l = m_ValueStack.Pop();
 
-			double? rn = r.AsNumber();
-			double? ln = l.AsNumber();
+			double? rn = r.CastToNumber();
+			double? ln = l.CastToNumber();
 
 			if (ln.HasValue && rn.HasValue)
 			{
-				m_ValueStack.Push(new RValue(Math.IEEERemainder(ln.Value, rn.Value)));
+				m_ValueStack.Push(DynValue.NewNumber(Math.IEEERemainder(ln.Value, rn.Value)));
 				return instructionPtr;
 			}
 			else
@@ -697,15 +678,15 @@ namespace MoonSharp.Interpreter.Execution.VM
 
 		private int ExecDiv(Instruction i, int instructionPtr)
 		{
-			RValue r = m_ValueStack.Pop();
-			RValue l = m_ValueStack.Pop();
+			DynValue r = m_ValueStack.Pop();
+			DynValue l = m_ValueStack.Pop();
 
-			double? rn = r.AsNumber();
-			double? ln = l.AsNumber();
+			double? rn = r.CastToNumber();
+			double? ln = l.CastToNumber();
 
 			if (ln.HasValue && rn.HasValue)
 			{
-				m_ValueStack.Push(new RValue(ln.Value / rn.Value));
+				m_ValueStack.Push(DynValue.NewNumber(ln.Value / rn.Value));
 				return instructionPtr;
 			}
 			else
@@ -717,15 +698,15 @@ namespace MoonSharp.Interpreter.Execution.VM
 		}
 		private int ExecPower(Instruction i, int instructionPtr)
 		{
-			RValue r = m_ValueStack.Pop();
-			RValue l = m_ValueStack.Pop();
+			DynValue r = m_ValueStack.Pop();
+			DynValue l = m_ValueStack.Pop();
 
-			double? rn = r.AsNumber();
-			double? ln = l.AsNumber();
+			double? rn = r.CastToNumber();
+			double? ln = l.CastToNumber();
 
 			if (ln.HasValue && rn.HasValue)
 			{
-				m_ValueStack.Push(new RValue(Math.Pow(ln.Value, rn.Value)));
+				m_ValueStack.Push(DynValue.NewNumber(Math.Pow(ln.Value, rn.Value)));
 				return instructionPtr;
 			}
 			else
@@ -740,52 +721,47 @@ namespace MoonSharp.Interpreter.Execution.VM
 
 		private int ExecNeg(Instruction i, int instructionPtr)
 		{
-			RValue r = m_ValueStack.Pop();
-			double? rn = r.AsNumber();
+			DynValue r = m_ValueStack.Pop();
+			double? rn = r.CastToNumber();
 
 			if (rn.HasValue)
 			{
-				m_ValueStack.Push(new RValue(-rn.Value));
+				m_ValueStack.Push(DynValue.NewNumber(-rn.Value));
 				return instructionPtr;
 			}
-
-			if (r.Type == DataType.Number)
-				m_ValueStack.Push(new RValue(-r.Number));
 			else
 			{
 				int ip = Internal_InvokeUnaryMetaMethod(r, "__unm", instructionPtr);
 				if (ip >= 0) return ip;
 				else throw new ScriptRuntimeException(null, "Arithmetic on non number");
 			}
-
-			return instructionPtr;
 		}
 
 
 		private int ExecEq(Instruction i, int instructionPtr)
 		{
-			RValue r = m_ValueStack.Pop();
-			RValue l = m_ValueStack.Pop();
+			DynValue r = m_ValueStack.Pop();
+			DynValue l = m_ValueStack.Pop();
 
 			if (object.ReferenceEquals(r, l))
 			{
-				m_ValueStack.Push(new RValue(true));
+				m_ValueStack.Push(DynValue.True);
 			}
 			else if (r.Type != l.Type)
 			{
-				m_ValueStack.Push(new RValue(false));
+				m_ValueStack.Push(DynValue.False);
 			}
 			else if ((l.Type == DataType.Table || l.Type == DataType.UserData) && (l.Meta != null) && (l.Meta == r.Meta))
 			{
 				int ip = Internal_InvokeBinaryMetaMethod(l, r, "__eq", instructionPtr);
 				if (ip < 0)
-					m_ValueStack.Push(new RValue(r.Equals(l)));
+					m_ValueStack.Push(DynValue.NewBoolean(r.Equals(l)));
 				else
 					return ip;
 			}
 			else
 			{
-				m_ValueStack.Push(new RValue(r.Equals(l)));
+				m_ValueStack.Push(DynValue.NewBoolean(r.Equals(l)));
 			}
 
 			return instructionPtr;
@@ -793,16 +769,16 @@ namespace MoonSharp.Interpreter.Execution.VM
 
 		private int ExecLess(Instruction i, int instructionPtr)
 		{
-			RValue r = m_ValueStack.Pop();
-			RValue l = m_ValueStack.Pop();
+			DynValue r = m_ValueStack.Pop();
+			DynValue l = m_ValueStack.Pop();
 
 			if (l.Type == DataType.Number && r.Type == DataType.Number)
 			{
-				m_ValueStack.Push(new RValue(l.Number < r.Number));
+				m_ValueStack.Push(DynValue.NewBoolean(l.Number < r.Number));
 			}
 			else if (l.Type == DataType.String && r.Type == DataType.String)
 			{
-				m_ValueStack.Push(new RValue(l.String.CompareTo(r.String) < 0));
+				m_ValueStack.Push(DynValue.NewBoolean(l.String.CompareTo(r.String) < 0));
 			}
 			else
 			{
@@ -818,16 +794,16 @@ namespace MoonSharp.Interpreter.Execution.VM
 
 		private int ExecLessEq(Instruction i, int instructionPtr)
 		{
-			RValue r = m_ValueStack.Pop();
-			RValue l = m_ValueStack.Pop();
+			DynValue r = m_ValueStack.Pop();
+			DynValue l = m_ValueStack.Pop();
 
 			if (l.Type == DataType.Number && r.Type == DataType.Number)
 			{
-				m_ValueStack.Push(new RValue(l.Number <= r.Number));
+				m_ValueStack.Push(DynValue.NewBoolean(l.Number <= r.Number));
 			}
 			else if (l.Type == DataType.String && r.Type == DataType.String)
 			{
-				m_ValueStack.Push(new RValue(l.String.CompareTo(r.String) <= 0));
+				m_ValueStack.Push(DynValue.NewBoolean(l.String.CompareTo(r.String) <= 0));
 			}
 			else
 			{
@@ -850,17 +826,17 @@ namespace MoonSharp.Interpreter.Execution.VM
 
 		private int ExecLen(Instruction i, int instructionPtr)
 		{
-			RValue r = m_ValueStack.Pop();
+			DynValue r = m_ValueStack.Pop();
 
 			if (r.Type == DataType.String)
-				m_ValueStack.Push(new RValue(r.String.Length));
+				m_ValueStack.Push(DynValue.NewNumber(r.String.Length));
 			else
 			{
 				int ip = Internal_InvokeUnaryMetaMethod(r, "__len", instructionPtr);
 				if (ip >= 0) 
 					return ip;
 				else if (r.Type == DataType.Table)
-					m_ValueStack.Push(new RValue(r.Table.Length));
+					m_ValueStack.Push(DynValue.NewNumber(r.Table.Length));
 				else 
 					throw new ScriptRuntimeException(null, "Arithmetic on non number");
 			}
@@ -870,15 +846,15 @@ namespace MoonSharp.Interpreter.Execution.VM
 
 		private int ExecConcat(Instruction i, int instructionPtr)
 		{
-			RValue r = m_ValueStack.Pop();
-			RValue l = m_ValueStack.Pop();
+			DynValue r = m_ValueStack.Pop();
+			DynValue l = m_ValueStack.Pop();
 
-			string rs = r.AsSimpleString();
-			string ls = l.AsSimpleString();
+			string rs = r.CastToString();
+			string ls = l.CastToString();
 
 			if (rs != null && ls != null)
 			{
-				m_ValueStack.Push(new RValue(ls + rs));
+				m_ValueStack.Push(DynValue.NewString(ls + rs));
 				return instructionPtr;
 			}
 			else

+ 25 - 22
src/MoonSharp.Interpreter/Execution/VM/Processor/Processor_Scope.cs

@@ -18,7 +18,7 @@ namespace MoonSharp.Interpreter.Execution.VM
 			if (to >= 0 && from >= 0)
 			{
 				for (int i = from; i <= to; i++)
-					array[i] = new RValue();
+					array[i] = DynValue.NewNil();
 			}
 		}
 
@@ -36,60 +36,60 @@ namespace MoonSharp.Interpreter.Execution.VM
 		}
 
 
-		public RValue GetGenericSymbol(LRef symref)
+		public DynValue GetGenericSymbol(SymbolRef symref)
 		{
 			switch (symref.i_Type)
 			{
-				case LRefType.Global:
+				case SymbolRefType.Global:
 					return m_GlobalTable[symref.i_Name];
-				case LRefType.Local:
+				case SymbolRefType.Local:
 					return m_ExecutionStack.Peek().LocalScope[symref.i_Index];
-				case LRefType.Upvalue:
+				case SymbolRefType.Upvalue:
 					return m_ExecutionStack.Peek().ClosureScope[symref.i_Index];
-				case LRefType.Index:
-				case LRefType.Invalid:
+				case SymbolRefType.Index:
+				case SymbolRefType.Invalid:
 				default:
 					throw new InternalErrorException("Unexpected {0} LRef at resolution: {1}", symref.i_Type, symref.i_Name);
 			}
 		}
 
-		public void AssignGenericSymbol(LRef symref, RValue value)
+		public void AssignGenericSymbol(SymbolRef symref, DynValue value)
 		{
 			switch (symref.i_Type)
 			{
-				case LRefType.Global:
+				case SymbolRefType.Global:
 					m_GlobalTable[symref.i_Name] = value.CloneAsWritable();
 					break;
-				case LRefType.Local:
+				case SymbolRefType.Local:
 					{
 						var stackframe = m_ExecutionStack.Peek();
 
-						RValue v = stackframe.LocalScope[symref.i_Index];
+						DynValue v = stackframe.LocalScope[symref.i_Index];
 						if (v == null)
-							stackframe.LocalScope[symref.i_Index] = v = new RValue();
+							stackframe.LocalScope[symref.i_Index] = v = DynValue.NewNil();
 
 						v.Assign(value);
 					}
 					break;
-				case LRefType.Upvalue:
+				case SymbolRefType.Upvalue:
 					{
 						var stackframe = m_ExecutionStack.Peek();
 
-						RValue v = stackframe.ClosureScope[symref.i_Index];
+						DynValue v = stackframe.ClosureScope[symref.i_Index];
 						if (v == null)
-							stackframe.ClosureScope[symref.i_Index] = v = new RValue();
+							stackframe.ClosureScope[symref.i_Index] = v = DynValue.NewNil();
 
 						v.Assign(value);
 					}
 					break;
-				case LRefType.Index:
-				case LRefType.Invalid:
+				case SymbolRefType.Index:
+				case SymbolRefType.Invalid:
 				default:
 					throw new InternalErrorException("Unexpected {0} LRef at resolution: {1}", symref.i_Type, symref.i_Name);
 			}
 		}
 
-		public LRef FindRefByName(string name)
+		public SymbolRef FindRefByName(string name)
 		{
 			var stackframe = m_ExecutionStack.Peek();
 
@@ -107,12 +107,15 @@ namespace MoonSharp.Interpreter.Execution.VM
 			
 			var closure = stackframe.ClosureScope;
 
-			for (int i = 0; i < closure.Symbols.Length; i++)
-				if (closure.Symbols[i] == name)
-					return LRef.Upvalue(name, i);
+			if (closure != null)
+			{
+				for (int i = 0; i < closure.Symbols.Length; i++)
+					if (closure.Symbols[i] == name)
+						return SymbolRef.Upvalue(name, i);
+			}
 
 			if (m_GlobalTable.HasStringSymbol(name))
-				return LRef.Global(name);
+				return SymbolRef.Global(name);
 
 			return null;
 		}

+ 51 - 11
src/MoonSharp.Interpreter/Execution/VM/Processor/Processor_UtilityFunctions.cs

@@ -9,13 +9,53 @@ namespace MoonSharp.Interpreter.Execution.VM
 {
 	sealed partial class Processor
 	{
-		private int Internal_InvokeUnaryMetaMethod(RValue op1, string eventName, int instructionPtr)
+		private DynValue[] Internal_AdjustTuple(IList<DynValue> values)
 		{
-			RValue m = null;
+			if (values == null || values.Count == 0)
+				return new DynValue[0];
+
+			if (values[values.Count - 1].Type == DataType.Tuple)
+			{
+				int baseLen = values.Count - 1 + values[values.Count - 1].Tuple.Length;
+				DynValue[] result = new DynValue[baseLen];
+
+				for (int i = 0; i < values.Count - 1; i++)
+				{
+					result[i] = values[i].ToScalar();
+				}
+
+				for (int i = 0; i < values[values.Count - 1].Tuple.Length; i++)
+				{
+					result[values.Count + i - 1] = values[values.Count - 1].Tuple[i];
+				}
+
+				if (result[result.Length - 1].Type == DataType.Tuple)
+					return Internal_AdjustTuple(result);
+				else
+					return result;
+			}
+			else
+			{
+				DynValue[] result = new DynValue[values.Count];
+
+				for (int i = 0; i < values.Count; i++)
+				{
+					result[i] = values[i].ToScalar();
+				}
+
+				return result;
+			}
+		}
+
+
+
+		private int Internal_InvokeUnaryMetaMethod(DynValue op1, string eventName, int instructionPtr)
+		{
+			DynValue m = null;
 
 			if (op1.Meta != null)
 			{
-				RValue meta1 = op1.Meta.Table.RawGet(eventName);
+				DynValue meta1 = op1.Meta.Table.RawGet(eventName);
 				if (meta1 != null && meta1.Type != DataType.Nil)
 					m = meta1;
 			}
@@ -31,7 +71,7 @@ namespace MoonSharp.Interpreter.Execution.VM
 				return -1;
 			}
 		}
-		private int Internal_InvokeBinaryMetaMethod(RValue l, RValue r, string eventName, int instructionPtr)
+		private int Internal_InvokeBinaryMetaMethod(DynValue l, DynValue r, string eventName, int instructionPtr)
 		{
 			var m = Internal_GetBinHandler(l, r, eventName);
 
@@ -48,17 +88,17 @@ namespace MoonSharp.Interpreter.Execution.VM
 			}
 		}
 
-		private RValue Internal_GetBinHandler(RValue op1, RValue op2, string eventName)
+		private DynValue Internal_GetBinHandler(DynValue op1, DynValue op2, string eventName)
 		{
 			if (op1.Meta != null)
 			{
-				RValue meta1 = op1.Meta.Table.RawGet(eventName);
+				DynValue meta1 = op1.Meta.Table.RawGet(eventName);
 				if (meta1 != null && meta1.Type != DataType.Nil)
 					return meta1;
 			}
 			if (op2.Meta != null)
 			{
-				RValue meta2 = op2.Meta.Table.RawGet(eventName);
+				DynValue meta2 = op2.Meta.Table.RawGet(eventName);
 				if (meta2 != null && meta2.Type != DataType.Nil)
 					return meta2;
 			}
@@ -66,9 +106,9 @@ namespace MoonSharp.Interpreter.Execution.VM
 		}
 
 
-		private RValue[] StackTopToArray(int items, bool pop)
+		private DynValue[] StackTopToArray(int items, bool pop)
 		{
-			RValue[] values = new RValue[items];
+			DynValue[] values = new DynValue[items];
 
 			if (pop)
 			{
@@ -88,9 +128,9 @@ namespace MoonSharp.Interpreter.Execution.VM
 			return values;
 		}
 
-		private RValue[] StackTopToArrayReverse(int items, bool pop)
+		private DynValue[] StackTopToArrayReverse(int items, bool pop)
 		{
-			RValue[] values = new RValue[items];
+			DynValue[] values = new DynValue[items];
 
 			if (pop)
 			{

+ 30 - 0
src/MoonSharp.Interpreter/Modules/CoreModules.cs

@@ -0,0 +1,30 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+
+namespace MoonSharp.Interpreter
+{
+	[Flags]
+	public enum CoreModules
+	{
+		GlobalConsts = 0x1,
+		TableIterators = 0x2,
+		Metatables = 0x4,
+
+
+		Preset_HardSandbox = GlobalConsts | TableIterators,
+		Preset_SoftSandbox = Preset_HardSandbox | Metatables,
+		Preset_Default = Preset_SoftSandbox,
+	}
+
+	public static class CoreModules_ExtensionMethods
+	{
+		public static bool Has(this CoreModules val, CoreModules flag)
+		{
+			return (val & flag) == flag;
+		}
+	}
+
+
+}

+ 32 - 7
src/MoonSharp.Interpreter/Modules/ModuleRegister.cs

@@ -3,12 +3,37 @@ using System.Collections.Generic;
 using System.Linq;
 using System.Reflection;
 using System.Text;
+using MoonSharp.Interpreter.CoreLib;
 using MoonSharp.Interpreter.Execution;
 
 namespace MoonSharp.Interpreter
 {
 	public static class ModuleRegister
 	{
+		public static Table RegisterCoreModules(this Table table, CoreModules modules)
+		{
+			if (modules.Has(CoreModules.GlobalConsts)) RegisterConstants(table);
+			if (modules.Has(CoreModules.TableIterators)) RegisterModuleType<TableIterators>(table);
+			if (modules.Has(CoreModules.Metatables)) RegisterModuleType<MetaTableMethods>(table);
+
+			return table;
+		}
+
+
+
+		public static Table RegisterConstants(this Table table)
+		{
+			table["_G"] = DynValue.NewTable(table);
+			table["_VERSION"] = DynValue.NewString(string.Format("Moon# {0}", 
+				Assembly.GetExecutingAssembly().GetName().Version.Major,
+				Assembly.GetExecutingAssembly().GetName().Version.Minor));
+			table["_MOONSHARP"] = DynValue.NewString(Assembly.GetExecutingAssembly().GetName().Version.ToString());
+
+			return table;
+		}
+
+
+
 		public static Table RegisterModuleType(this Table table, Type t)
 		{
 			foreach (MethodInfo mi in t.GetMethods(BindingFlags.Static | BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.NonPublic).Where(_mi => _mi.GetCustomAttributes(typeof(MoonSharpMethodAttribute), false).Length > 0))
@@ -18,16 +43,16 @@ namespace MoonSharp.Interpreter
 				ParameterInfo[] pi = mi.GetParameters();
 
 				if (pi.Length != 2 || pi[0].ParameterType != typeof(IExecutionContext)
-					|| pi[1].ParameterType != typeof(CallbackArguments) || mi.ReturnType != typeof(RValue))
+					|| pi[1].ParameterType != typeof(CallbackArguments) || mi.ReturnType != typeof(DynValue))
 				{
 					throw new ArgumentException(string.Format("Method {0} does not have the right signature.", mi.Name));
 				}
 
-				Func<IExecutionContext, CallbackArguments, RValue> func = (Func<IExecutionContext, CallbackArguments, RValue>)Delegate.CreateDelegate(typeof(Func<IExecutionContext, CallbackArguments, RValue>), mi);
+				Func<IExecutionContext, CallbackArguments, DynValue> func = (Func<IExecutionContext, CallbackArguments, DynValue>)Delegate.CreateDelegate(typeof(Func<IExecutionContext, CallbackArguments, DynValue>), mi);
 
 				string name = (!string.IsNullOrEmpty(attr.Name)) ? attr.Name : mi.Name;
 
-				table[name] = new RValue(new CallbackFunction(func));
+				table[name] = DynValue.NewCallback(func);
 			}
 
 			return table;
@@ -49,17 +74,17 @@ namespace MoonSharp.Interpreter
 				ParameterInfo[] pi = mi.GetParameters();
 
 				if (pi.Length != 2 || pi[0].ParameterType != typeof(IExecutionContext)
-					|| pi[1].ParameterType != typeof(CallbackArguments) || mi.ReturnType != typeof(RValue))
+					|| pi[1].ParameterType != typeof(CallbackArguments) || mi.ReturnType != typeof(DynValue))
 				{
 					throw new ArgumentException(string.Format("Method {0} does not have the right signature.", mi.Name));
 				}
 
-				Func<IExecutionContext, CallbackArguments, RValue> func = (Func<IExecutionContext, CallbackArguments, RValue>)
-					Delegate.CreateDelegate(typeof(Func<IExecutionContext, CallbackArguments, RValue>), o, mi);
+				Func<IExecutionContext, CallbackArguments, DynValue> func = (Func<IExecutionContext, CallbackArguments, DynValue>)
+					Delegate.CreateDelegate(typeof(Func<IExecutionContext, CallbackArguments, DynValue>), o, mi);
 
 				string name = (!string.IsNullOrEmpty(attr.Name)) ? attr.Name : mi.Name;
 
-				table[name] = new RValue(new CallbackFunction(func));
+				table[name] = DynValue.NewCallback(func);
 			}
 
 			return table;

+ 17 - 8
src/MoonSharp.Interpreter/MoonSharp.Interpreter.csproj

@@ -30,8 +30,9 @@
     <DefineConstants>DEBUG;TRACE</DefineConstants>
     <ErrorReport>prompt</ErrorReport>
     <WarningLevel>4</WarningLevel>
-    <NoWarn>3021</NoWarn>
+    <NoWarn>3021, 1591</NoWarn>
     <Prefer32Bit>false</Prefer32Bit>
+    <DocumentationFile>bin\Debug\MoonSharp.Interpreter.XML</DocumentationFile>
   </PropertyGroup>
   <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
     <DebugType>pdbonly</DebugType>
@@ -74,7 +75,8 @@
   </ItemGroup>
   <ItemGroup>
     <Compile Include="CoreLib\BasicMethods.cs" />
-    <Compile Include="CoreLib\CoreLibModule.cs" />
+    <Compile Include="CoreLib\ErrorHandling.cs" />
+    <Compile Include="CoreLib\LoadMethods.cs" />
     <Compile Include="CoreLib\MetaTableMethods.cs" />
     <Compile Include="CoreLib\TableIterators.cs" />
     <Compile Include="DataStructs\Extension_Methods.cs" />
@@ -96,12 +98,15 @@
     <Compile Include="Execution\DataTypes\Closure.cs" />
     <Compile Include="Execution\DataTypes\CallbackFunction.cs" />
     <Compile Include="Execution\DataTypes\TablePair.cs" />
-    <Compile Include="Execution\IExecutionContext.cs" />
+    <Compile Include="Execution\FileLoadRequestedEventArgs.cs" />
+    <Compile Include="Execution\IExecutionContext.cs">
+      <SubType>Code</SubType>
+    </Compile>
     <Compile Include="Execution\Scopes\ClosureContext.cs" />
     <Compile Include="Execution\Scopes\LoopTracker.cs" />
     <Compile Include="Execution\Scopes\IClosureBuilder.cs" />
-    <Compile Include="Execution\DataTypes\LRefType.cs" />
-    <Compile Include="Execution\DataTypes\LRef.cs" />
+    <Compile Include="Execution\DataTypes\SymbolRefType.cs" />
+    <Compile Include="Execution\DataTypes\SymbolRef.cs" />
     <Compile Include="Execution\Scopes\BuildTimeScope.cs" />
     <Compile Include="Execution\Scopes\BuildTimeScopeBlock.cs" />
     <Compile Include="Execution\Scopes\BuildTimeScopeFrame.cs" />
@@ -109,10 +114,10 @@
     <Compile Include="Execution\Scopes\RuntimeScopeFrame.cs" />
     <Compile Include="Execution\ScriptLoadingContext.cs" />
     <Compile Include="Execution\DataTypes\DataType.cs" />
-    <Compile Include="Execution\DataTypes\RValue.cs" />
+    <Compile Include="Execution\DataTypes\DynValue.cs" />
     <Compile Include="Execution\Script.cs" />
     <Compile Include="Execution\DataTypes\Table.cs" />
-    <Compile Include="Execution\VM\Chunk.cs" />
+    <Compile Include="Execution\VM\ByteCode.cs" />
     <Compile Include="DataStructs\FastStack.cs" />
     <Compile Include="Execution\VM\LoopTracker.cs" />
     <Compile Include="Execution\VM\Instruction.cs" />
@@ -132,6 +137,7 @@
     <Compile Include="Grammar\Lua.g4.parser.cs">
       <DependentUpon>Lua.g4</DependentUpon>
     </Compile>
+    <Compile Include="Modules\CoreModules.cs" />
     <Compile Include="Modules\ModuleRegister.cs">
       <SubType>Code</SubType>
     </Compile>
@@ -139,6 +145,7 @@
     <Compile Include="Modules\MoonSharpModuleAttribute.cs">
       <SubType>Code</SubType>
     </Compile>
+    <Compile Include="Tree\Expressions\AdjustmentExpression.cs" />
     <Compile Include="Tree\IVariable.cs" />
     <Compile Include="MoonSharpInterpreter.cs" />
     <Compile Include="Properties\AssemblyInfo.cs" />
@@ -155,7 +162,9 @@
     <Compile Include="Tree\NodeBase.cs" />
     <Compile Include="Tree\NodeFactory.cs" />
     <Compile Include="Tree\Statements\AssignmentStatement.cs" />
-    <Compile Include="Tree\Statements\ChunkStatement.cs" />
+    <Compile Include="Tree\Statements\ChunkStatement.cs">
+      <SubType>Code</SubType>
+    </Compile>
     <Compile Include="Tree\Statements\CompositeStatement.cs" />
     <Compile Include="Tree\Statements\BreakStatement.cs" />
     <Compile Include="Tree\Statements\ForEachLoopStatement.cs" />

+ 1 - 36
src/MoonSharp.Interpreter/MoonSharpInterpreter.cs

@@ -21,45 +21,10 @@ namespace MoonSharp.Interpreter
 			LuaStrict
 		}
 
-		private static Script LoadFromICharStream(ICharStream charStream)
-		{
-			LuaLexer lexer;
-			LuaParser parser;
-
-			using (var _ = new CodeChrono("MoonSharpScript.LoadFromICharStream/AST"))
-			{
-				lexer = new LuaLexer(charStream);
-				parser = new LuaParser(new CommonTokenStream(lexer));
-			}
-#if DEBUG
-			AstDump astDump = new AstDump();
-			astDump.DumpTree(parser.chunk(), @"c:\temp\treedump.txt");
-			parser.Reset();
-#endif
-			using (var _ = new CodeChrono("MoonSharpScript.LoadFromICharStream/EXE"))
-			{
-				var lcontext = new ScriptLoadingContext() { Scope = new BuildTimeScope() };
-				ChunkStatement stat = new ChunkStatement(parser.chunk(), lcontext);
-				return new Script(stat, lcontext);
-			}
-		}
-
-
-		public static Script LoadFromFile(string filename)
-		{
-			return LoadFromICharStream(new AntlrFileStream(filename));
-		}
-
-		public static Script LoadFromString(string text)
-		{
-			return LoadFromICharStream(new AntlrInputStream(text));
-		}
-
-
 
 		public static void WarmUp()
 		{
-			LoadFromString("return 1;");
+			//LoadFromString("return 1;");
 		}
 	}
 }

+ 29 - 0
src/MoonSharp.Interpreter/Tree/Expressions/AdjustmentExpression.cs

@@ -0,0 +1,29 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using Antlr4.Runtime.Tree;
+using MoonSharp.Interpreter.Execution;
+using MoonSharp.Interpreter.Grammar;
+
+namespace MoonSharp.Interpreter.Tree.Expressions
+{
+	class AdjustmentExpression : Expression 
+	{
+		private Expression expression;
+
+		public AdjustmentExpression(IParseTree tree, ScriptLoadingContext lcontext, IParseTree subtree)
+			: base(tree, lcontext)
+		{
+			expression = NodeFactory.CreateExpression(subtree, lcontext);
+		}
+
+		public override void Compile(Execution.VM.ByteCode bc)
+		{
+			expression.Compile(bc);
+			bc.Scalar();
+		}
+
+
+	}
+}

+ 1 - 1
src/MoonSharp.Interpreter/Tree/Expressions/ExprListExpression.cs

@@ -26,7 +26,7 @@ namespace MoonSharp.Interpreter.Tree.Expressions
 			return expressions;
 		}
 
-		public override void Compile(Execution.VM.Chunk bc)
+		public override void Compile(Execution.VM.ByteCode bc)
 		{
 			foreach (var exp in expressions)
 				exp.Compile(bc);

+ 1 - 1
src/MoonSharp.Interpreter/Tree/Expressions/FunctionCallChainExpression.cs

@@ -40,7 +40,7 @@ namespace MoonSharp.Interpreter.Tree.Expressions
 		{ }
 
 
-		public override void Compile(Execution.VM.Chunk bc)
+		public override void Compile(Execution.VM.ByteCode bc)
 		{
 			m_StartingExpression.Compile(bc);
 

+ 9 - 9
src/MoonSharp.Interpreter/Tree/Expressions/FunctionDefinitionExpression.cs

@@ -10,10 +10,10 @@ namespace MoonSharp.Interpreter.Tree.Expressions
 {
 	class FunctionDefinitionExpression : Expression, IClosureBuilder
 	{
-		LRef[] m_ParamNames;
+		SymbolRef[] m_ParamNames;
 		Statement m_Statement;
 		RuntimeScopeFrame m_StackFrame;
-		List<LRef> m_Closure = new List<LRef>();
+		List<SymbolRef> m_Closure = new List<SymbolRef>();
 		public object UpvalueCreationTag { get; set; }
 
 		public FunctionDefinitionExpression(LuaParser.AnonfunctiondefContext context, ScriptLoadingContext lcontext, bool pushSelfParam = false)
@@ -21,18 +21,18 @@ namespace MoonSharp.Interpreter.Tree.Expressions
 		{
 		}
 
-		public LRef CreateUpvalue(BuildTimeScope scope, LRef symbol)
+		public SymbolRef CreateUpvalue(BuildTimeScope scope, SymbolRef symbol)
 		{
 			for (int i = 0; i < m_Closure.Count; i++)
 			{
 				if (m_Closure[i].i_Name == symbol.i_Name)
 				{
-					return LRef.Upvalue(symbol.i_Name, i);
+					return SymbolRef.Upvalue(symbol.i_Name, i);
 				}
 			}
 
 			m_Closure.Add(symbol);
-			return LRef.Upvalue(symbol.i_Name, m_Closure.Count - 1);
+			return SymbolRef.Upvalue(symbol.i_Name, m_Closure.Count - 1);
 		}
 
 		public FunctionDefinitionExpression(LuaParser.FuncbodyContext context, ScriptLoadingContext lcontext, bool pushSelfParam = false)
@@ -82,9 +82,9 @@ namespace MoonSharp.Interpreter.Tree.Expressions
 			lcontext.Scope.LeaveClosure();
 		}
 
-		private LRef[] DefineArguments(string[] paramnames, ScriptLoadingContext lcontext)
+		private SymbolRef[] DefineArguments(string[] paramnames, ScriptLoadingContext lcontext)
 		{
-			LRef[] ret = new LRef[paramnames.Length];
+			SymbolRef[] ret = new SymbolRef[paramnames.Length];
 
 			for (int i = 0; i < paramnames.Length; i++)
 				ret[i] = lcontext.Scope.DefineLocal(paramnames[i]);
@@ -94,7 +94,7 @@ namespace MoonSharp.Interpreter.Tree.Expressions
 
 
 
-		public void Compile(Chunk bc, Action afterDecl, string friendlyName)
+		public void Compile(ByteCode bc, Action afterDecl, string friendlyName)
 		{
 			bc.Closure(m_Closure.ToArray(), bc.GetJumpPointForNextInstruction() + 3);
 			afterDecl();
@@ -114,7 +114,7 @@ namespace MoonSharp.Interpreter.Tree.Expressions
 		}
 
 
-		public override void Compile(Chunk bc)
+		public override void Compile(ByteCode bc)
 		{
 			Compile(bc, () => bc.Nop(null), null);
 		}

+ 2 - 2
src/MoonSharp.Interpreter/Tree/Expressions/IndexExpression.cs

@@ -23,7 +23,7 @@ namespace MoonSharp.Interpreter.Tree.Expressions
 
 
 
-		public override void Compile(Chunk bc)
+		public override void Compile(ByteCode bc)
 		{
 			m_BaseExp.Compile(bc);
 			m_IndexExp.Compile(bc);
@@ -31,7 +31,7 @@ namespace MoonSharp.Interpreter.Tree.Expressions
 		}
 
 
-		public void CompileAssignment(Chunk bc)
+		public void CompileAssignment(ByteCode bc)
 		{
 			m_BaseExp.Compile(bc);
 			m_IndexExp.Compile(bc);

+ 7 - 7
src/MoonSharp.Interpreter/Tree/Expressions/LiteralExpression.cs

@@ -11,9 +11,9 @@ namespace MoonSharp.Interpreter.Tree.Expressions
 {
 	class LiteralExpression : Expression
 	{
-		RValue m_Value;
+		DynValue m_Value;
 
-		public LiteralExpression(IParseTree context, ScriptLoadingContext lcontext, RValue rvalue)
+		public LiteralExpression(IParseTree context, ScriptLoadingContext lcontext, DynValue rvalue)
 			: base(context, lcontext)
 		{
 			m_Value = rvalue.AsReadOnly();
@@ -37,11 +37,11 @@ namespace MoonSharp.Interpreter.Tree.Expressions
 			ITerminalNode normStr = context.NORMALSTRING();
 
 			if (charStr != null)
-				m_Value = new RValue(NormalizeCharStr(charStr.GetText())).AsReadOnly();
+				m_Value = DynValue.NewString(NormalizeCharStr(charStr.GetText())).AsReadOnly();
 			else if (longStr != null)
-				m_Value = new RValue(NormalizeLongStr(longStr.GetText())).AsReadOnly();
+				m_Value = DynValue.NewString(NormalizeLongStr(longStr.GetText())).AsReadOnly();
 			else if (normStr != null)
-				m_Value = new RValue(NormalizeNormStr(normStr.GetText())).AsReadOnly();
+				m_Value = DynValue.NewString(NormalizeNormStr(normStr.GetText())).AsReadOnly();
 		}
 
 		private string NormalizeNormStr(string str)
@@ -83,10 +83,10 @@ namespace MoonSharp.Interpreter.Tree.Expressions
 
 			string txt = terminalNode.GetText();
 			double val = parser(txt);
-			m_Value = new RValue(val).AsReadOnly();
+			m_Value = DynValue.NewNumber(val).AsReadOnly();
 		}
 
-		public override void Compile(Execution.VM.Chunk bc)
+		public override void Compile(Execution.VM.ByteCode bc)
 		{
 			bc.Literal(m_Value);
 		}

+ 1 - 1
src/MoonSharp.Interpreter/Tree/Expressions/OperatorExpression.cs

@@ -127,7 +127,7 @@ namespace MoonSharp.Interpreter.Tree.Expressions
 			return (tree.EnumChilds().Any(t => s_OperatorTypes.Contains(t.GetType())));
 		}
 
-		public override void Compile(Execution.VM.Chunk bc)
+		public override void Compile(Execution.VM.ByteCode bc)
 		{
 			m_Exp1.Compile(bc);
 

+ 3 - 3
src/MoonSharp.Interpreter/Tree/Expressions/SymbolRefExpression.cs

@@ -10,7 +10,7 @@ namespace MoonSharp.Interpreter.Tree.Expressions
 {
 	class SymbolRefExpression : Expression, IVariable
 	{
-		LRef m_Ref;
+		SymbolRef m_Ref;
 
 		public SymbolRefExpression(ITerminalNode terminalNode, ScriptLoadingContext lcontext)
 			: base(terminalNode, lcontext)
@@ -20,12 +20,12 @@ namespace MoonSharp.Interpreter.Tree.Expressions
 		}
 
 
-		public override void Compile(Execution.VM.Chunk bc)
+		public override void Compile(Execution.VM.ByteCode bc)
 		{
 			bc.Load(m_Ref);
 		}
 
-		public void CompileAssignment(Execution.VM.Chunk bc)
+		public void CompileAssignment(Execution.VM.ByteCode bc)
 		{
 			bc.Symbol(m_Ref);
 		}

+ 3 - 3
src/MoonSharp.Interpreter/Tree/Expressions/TableConstructor.cs

@@ -35,7 +35,7 @@ namespace MoonSharp.Interpreter.Tree.Expressions
 					else if (name != null)
 					{
 						m_CtorArgs.Add(new KeyValuePair<Expression, Expression>(
-							new LiteralExpression(field, lcontext, new RValue(name.GetText())),
+							new LiteralExpression(field, lcontext, DynValue.NewString(name.GetText())),
 							NodeFactory.CreateExpression(field.namedexp, lcontext)));
 					}
 					else 
@@ -49,7 +49,7 @@ namespace MoonSharp.Interpreter.Tree.Expressions
 
 
 
-		public override void Compile(Execution.VM.Chunk bc)
+		public override void Compile(Execution.VM.ByteCode bc)
 		{
 			bc.NewTable();
 
@@ -63,7 +63,7 @@ namespace MoonSharp.Interpreter.Tree.Expressions
 
 			for (int i = 0; i < m_PositionalValues.Count; i++)
 			{
-				bc.Literal(new RValue(i+1));
+				bc.Literal(DynValue.NewNumber(i+1));
 				bc.IndexRefN();
 				m_PositionalValues[i].Compile(bc);
 				bc.Store();

+ 2 - 2
src/MoonSharp.Interpreter/Tree/FunctionCall.cs

@@ -23,13 +23,13 @@ namespace MoonSharp.Interpreter.Tree
 			m_Arguments = nameAndArgs.args().children.SelectMany(t => NodeFactory.CreateExpressions(t, lcontext)).Where(t => t != null).ToArray();
 		}
 
-		public override void Compile(Execution.VM.Chunk bc)
+		public override void Compile(Execution.VM.ByteCode bc)
 		{
 			int argslen = m_Arguments.Length;
 
 			if (!string.IsNullOrEmpty(m_Name))
 			{
-				bc.Literal(new RValue(m_Name));
+				bc.Literal(DynValue.NewString(m_Name));
 				bc.Method();
 				++argslen;
 			}

+ 1 - 1
src/MoonSharp.Interpreter/Tree/IVariable.cs

@@ -8,6 +8,6 @@ namespace MoonSharp.Interpreter.Tree
 {
 	interface IVariable
 	{
-		void CompileAssignment(Execution.VM.Chunk bc);
+		void CompileAssignment(Execution.VM.ByteCode bc);
 	}
 }

+ 1 - 1
src/MoonSharp.Interpreter/Tree/Loop.cs

@@ -12,7 +12,7 @@ namespace MoonSharp.Interpreter.Tree
 		public RuntimeScopeBlock Scope;
 		public List<Instruction> BreakJumps = new List<Instruction>();
 
-		public void CompileBreak(Chunk bc)
+		public void CompileBreak(ByteCode bc)
 		{
 			bc.Exit(Scope);
 			BreakJumps.Add(bc.Jump(OpCode.Jump, -1));

+ 1 - 1
src/MoonSharp.Interpreter/Tree/NodeBase.cs

@@ -41,7 +41,7 @@ namespace MoonSharp.Interpreter.Tree
 				throw  RuntimeError(format, args);
 		}
 
-		public abstract void Compile(Chunk bc);
+		public abstract void Compile(ByteCode bc);
 
 
 

+ 18 - 4
src/MoonSharp.Interpreter/Tree/NodeFactory.cs

@@ -98,15 +98,29 @@ namespace MoonSharp.Interpreter.Tree
 		public static Expression CreateExpression(IParseTree tree, ScriptLoadingContext lcontext)
 		{
 			if (tree is LuaParser.VarOrExpContext)
+			{
+				// this whole rubbish just to detect adjustments to 1 arg of tuples
+				if ((tree.ChildCount > 0))
+				{
+					Antlr4.Runtime.Tree.TerminalNodeImpl token = tree.GetChild(0) as Antlr4.Runtime.Tree.TerminalNodeImpl;
+
+					if (token != null && token.GetText() == "(")
+					{
+						var subTree = tree.EnumChilds().Single(t => !(t is Antlr4.Runtime.Tree.TerminalNodeImpl));
+						return new AdjustmentExpression(tree, lcontext, subTree);
+					}
+				}
+
 				tree = tree.EnumChilds().Single(t => !(t is Antlr4.Runtime.Tree.TerminalNodeImpl));
+			}
 
 			if (tree is Antlr4.Runtime.Tree.TerminalNodeImpl)
 			{
 				string txt = tree.GetText();
 				if (txt == null) return null;
-				else if (txt == "nil") return new LiteralExpression(tree, lcontext, RValue.Nil);
-				else if (txt == "false") return new LiteralExpression(tree, lcontext, RValue.False);
-				else if (txt == "true") return new LiteralExpression(tree, lcontext, RValue.True);
+				else if (txt == "nil") return new LiteralExpression(tree, lcontext, DynValue.Nil);
+				else if (txt == "false") return new LiteralExpression(tree, lcontext, DynValue.False);
+				else if (txt == "true") return new LiteralExpression(tree, lcontext, DynValue.True);
 				else return null;
 			}
 
@@ -166,7 +180,7 @@ namespace MoonSharp.Interpreter.Tree
 				if (exp != null) 
 					indexExp = CreateExpression(exp, lcontext);
 				else
-					indexExp = new LiteralExpression(suff_NAME, lcontext, new RValue(suff_NAME.GetText()));
+					indexExp = new LiteralExpression(suff_NAME, lcontext, DynValue.NewString(suff_NAME.GetText()));
 
 				if (nameAndArgs != null)
 				{

+ 1 - 1
src/MoonSharp.Interpreter/Tree/Statements/AssignmentStatement.cs

@@ -29,7 +29,7 @@ namespace MoonSharp.Interpreter.Tree.Statements
 		}
 
 
-		public override void Compile(Execution.VM.Chunk bc)
+		public override void Compile(Execution.VM.ByteCode bc)
 		{
 			if (m_LValues.Length == 1 && m_RValues.Length == 1)
 			{

+ 1 - 1
src/MoonSharp.Interpreter/Tree/Statements/BreakStatement.cs

@@ -17,7 +17,7 @@ namespace MoonSharp.Interpreter.Tree.Statements
 
 
 
-		public override void Compile(Chunk bc)
+		public override void Compile(ByteCode bc)
 		{
 			bc.LoopTracker.Loops.Peek().CompileBreak(bc);
 		}

+ 44 - 2
src/MoonSharp.Interpreter/Tree/Statements/ChunkStatement.cs

@@ -1,8 +1,13 @@
-using System;
+#define DEBUG_COMPILER
+
+using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Text;
+using Antlr4.Runtime;
+using MoonSharp.Interpreter.Diagnostics;
 using MoonSharp.Interpreter.Execution;
+using MoonSharp.Interpreter.Execution.VM;
 using MoonSharp.Interpreter.Grammar;
 
 namespace MoonSharp.Interpreter.Tree.Statements
@@ -20,7 +25,7 @@ namespace MoonSharp.Interpreter.Tree.Statements
 			m_StackFrame = lcontext.Scope.PopFunction();
 		}
 
-		public override void Compile(Execution.VM.Chunk bc)
+		public override void Compile(Execution.VM.ByteCode bc)
 		{
 			bc.BeginFn(m_StackFrame, "<chunk-root>");
 			m_Block.Compile(bc);
@@ -28,5 +33,42 @@ namespace MoonSharp.Interpreter.Tree.Statements
 			//bc.Leave(m_StackFrame);
 		}
 
+		internal static int LoadFromICharStream(ICharStream charStream, string chunkName, ByteCode bytecode)
+		{
+			LuaLexer lexer;
+			LuaParser parser;
+
+			using (var _ = new CodeChrono("ChunkStatement.LoadFromICharStream/Parsing"))
+			{
+				lexer = new LuaLexer(charStream);
+				parser = new LuaParser(new CommonTokenStream(lexer));
+			}
+#if DEBUG_COMPILER
+			AstDump astDump = new AstDump();
+			astDump.DumpTree(parser.chunk(), @"c:\temp\treedump.txt");
+			parser.Reset();
+#endif
+			ChunkStatement stat;
+			using (var _ = new CodeChrono("ChunkStatement.LoadFromICharStream/AST"))
+			{
+				var lcontext = new ScriptLoadingContext() { Scope = new BuildTimeScope() };
+				stat = new ChunkStatement(parser.chunk(), lcontext);
+			}
+
+			int beginIp = -1;
+
+			using (var _ = new CodeChrono("ChunkStatement.LoadFromICharStream/Compile"))
+			{
+				bytecode.Nop(string.Format("Begin chunk {0}", chunkName));
+				beginIp = bytecode.GetJumpPointForLastInstruction();
+				stat.Compile(bytecode);
+				bytecode.Nop(string.Format("End chunk {0}", chunkName));
+#if DEBUG_COMPILER
+				bytecode.Dump(@"c:\temp\codedump.txt");
+#endif
+			}
+
+			return beginIp;
+		}
 	}
 }

+ 1 - 1
src/MoonSharp.Interpreter/Tree/Statements/CompositeStatement.cs

@@ -37,7 +37,7 @@ namespace MoonSharp.Interpreter.Tree.Statements
 		}
 
 
-		public override void Compile(Execution.VM.Chunk bc)
+		public override void Compile(Execution.VM.ByteCode bc)
 		{
 			if (m_Statements != null)
 			{

+ 3 - 3
src/MoonSharp.Interpreter/Tree/Statements/ForEachLoopStatement.cs

@@ -11,7 +11,7 @@ namespace MoonSharp.Interpreter.Tree.Statements
 	class ForEachLoopStatement : Statement
 	{
 		RuntimeScopeBlock m_StackFrame;
-		LRef[] m_Names;
+		SymbolRef[] m_Names;
 		Expression m_RValues;
 		Statement m_Block;
 
@@ -37,7 +37,7 @@ namespace MoonSharp.Interpreter.Tree.Statements
 			m_StackFrame = lcontext.Scope.PopBlock();
 		}
 
-		public override void Compile(Chunk bc)
+		public override void Compile(ByteCode bc)
 		{
 			//for var_1, ···, var_n in explist do block end
 
@@ -58,7 +58,7 @@ namespace MoonSharp.Interpreter.Tree.Statements
 			bc.Enter(m_StackFrame);
 
 			// push all iterating variables - stack : iterator-tuple, iter-var-symbols
-			foreach (LRef s in m_Names)
+			foreach (SymbolRef s in m_Names)
 				bc.Symbol(s);
 
 			// expand the tuple - stack : iterator-tuple, iter-var-symbols, f, var, s

+ 3 - 3
src/MoonSharp.Interpreter/Tree/Statements/ForLoopStatement.cs

@@ -14,7 +14,7 @@ namespace MoonSharp.Interpreter.Tree.Statements
 		//for' NAME '=' exp ',' exp (',' exp)? 'do' block 'end'
 		RuntimeScopeBlock m_StackFrame;
 		Statement m_InnerBlock;
-		LRef m_VarName;
+		SymbolRef m_VarName;
 		Expression m_Start, m_End, m_Step;
 
 		public ForLoopStatement(LuaParser.Stat_forloopContext context, ScriptLoadingContext lcontext)
@@ -28,7 +28,7 @@ namespace MoonSharp.Interpreter.Tree.Statements
 			if (exps.Length > 2)
 				m_Step = NodeFactory.CreateExpression(exps[2], lcontext);
 			else
-				m_Step = new LiteralExpression(context, lcontext, new RValue(1));
+				m_Step = new LiteralExpression(context, lcontext, DynValue.NewNumber(1));
 
 			lcontext.Scope.PushBlock();
 			m_VarName = lcontext.Scope.DefineLocal(context.NAME().GetText());
@@ -36,7 +36,7 @@ namespace MoonSharp.Interpreter.Tree.Statements
 			m_StackFrame = lcontext.Scope.PopBlock();
 		}
 
-		public override void Compile(Chunk bc)
+		public override void Compile(ByteCode bc)
 		{
 			Loop L = new Loop()
 			{

+ 1 - 1
src/MoonSharp.Interpreter/Tree/Statements/FunctionCallStatement.cs

@@ -21,7 +21,7 @@ namespace MoonSharp.Interpreter.Tree.Statements
 		}
 
 
-		public override void Compile(Chunk bc)
+		public override void Compile(ByteCode bc)
 		{
 			m_FunctionCallChain.Compile(bc);
 			bc.Pop();

+ 6 - 6
src/MoonSharp.Interpreter/Tree/Statements/FunctionDefinitionStatement.cs

@@ -10,7 +10,7 @@ namespace MoonSharp.Interpreter.Tree.Statements
 {
 	class FunctionDefinitionStatement : Statement
 	{
-		LRef m_FuncName;
+		SymbolRef m_FuncName;
 		List<string> m_TableAccessors;
 		string m_MethodName;
 		string m_FriendlyName;
@@ -53,7 +53,7 @@ namespace MoonSharp.Interpreter.Tree.Statements
 			}
 			else
 			{
-				m_FuncName = LRef.Global(fnname.Text);
+				m_FuncName = SymbolRef.Global(fnname.Text);
 				m_FriendlyName = fnname.Text;
 			}
 
@@ -70,12 +70,12 @@ namespace MoonSharp.Interpreter.Tree.Statements
 
 
 
-		public override void Compile(Execution.VM.Chunk bc)
+		public override void Compile(Execution.VM.ByteCode bc)
 		{
 			if (m_Local)
 			{
 				bc.Symbol(m_FuncName);
-				bc.Literal(RValue.Nil);
+				bc.Literal(DynValue.Nil);
 				bc.Store();
 				bc.Symbol(m_FuncName);
 				m_FuncDef.Compile(bc, () => bc.Store(), m_FriendlyName);
@@ -93,11 +93,11 @@ namespace MoonSharp.Interpreter.Tree.Statements
 
 				foreach (string str in m_TableAccessors)
 				{
-					bc.Literal(new RValue(str));
+					bc.Literal(DynValue.NewString(str));
 					bc.Index();
 				}
 
-				bc.Literal(new RValue(m_MethodName));
+				bc.Literal(DynValue.NewString(m_MethodName));
 
 				bc.IndexRef();
 

+ 1 - 1
src/MoonSharp.Interpreter/Tree/Statements/IfStatement.cs

@@ -50,7 +50,7 @@ namespace MoonSharp.Interpreter.Tree.Statements
 		}
 
 
-		public override void Compile(Execution.VM.Chunk bc)
+		public override void Compile(Execution.VM.ByteCode bc)
 		{
 			List<Instruction> endJumps = new List<Instruction>();
 

+ 1 - 1
src/MoonSharp.Interpreter/Tree/Statements/LabelStatement.cs

@@ -17,7 +17,7 @@ namespace MoonSharp.Interpreter.Tree.Statements
 			Label = context.label().NAME().GetText();
 		}
 
-		public override void Compile(Execution.VM.Chunk bc)
+		public override void Compile(Execution.VM.ByteCode bc)
 		{
 			throw new NotImplementedException();
 		}

+ 2 - 2
src/MoonSharp.Interpreter/Tree/Statements/LocalAssignmentStatement.cs

@@ -11,7 +11,7 @@ namespace MoonSharp.Interpreter.Tree.Statements
 {
 	class LocalAssignmentStatement : Statement
 	{
-		LRef[] m_Names;
+		SymbolRef[] m_Names;
 		Expression[] m_RValues;
 
 		public LocalAssignmentStatement(LuaParser.Stat_localassignmentContext context, ScriptLoadingContext lcontext)
@@ -36,7 +36,7 @@ namespace MoonSharp.Interpreter.Tree.Statements
 		}
 
 
-		public override void Compile(Execution.VM.Chunk bc)
+		public override void Compile(Execution.VM.ByteCode bc)
 		{
 			if (m_Names.Length == 1 && m_RValues.Length == 1)
 			{

+ 1 - 1
src/MoonSharp.Interpreter/Tree/Statements/NullStatement.cs

@@ -14,7 +14,7 @@ namespace MoonSharp.Interpreter.Tree.Statements
 		{ }
 
 
-		public override void Compile(Execution.VM.Chunk bc)
+		public override void Compile(Execution.VM.ByteCode bc)
 		{
 		}
 	}

+ 1 - 1
src/MoonSharp.Interpreter/Tree/Statements/RepeatStatement.cs

@@ -24,7 +24,7 @@ namespace MoonSharp.Interpreter.Tree.Statements
 		}
 
 
-		public override void Compile(Chunk bc)
+		public override void Compile(ByteCode bc)
 		{
 			Loop L = new Loop()
 			{

+ 1 - 1
src/MoonSharp.Interpreter/Tree/Statements/ReturnStatement.cs

@@ -21,7 +21,7 @@ namespace MoonSharp.Interpreter.Tree.Statements
 
 
 
-		public override void Compile(Execution.VM.Chunk bc)
+		public override void Compile(Execution.VM.ByteCode bc)
 		{
 			m_Expression.Compile(bc);
 			//bc.Exit();

+ 1 - 1
src/MoonSharp.Interpreter/Tree/Statements/ScopeBlockStatement.cs

@@ -20,7 +20,7 @@ namespace MoonSharp.Interpreter.Tree.Statements
 			m_StackFrame = lcontext.Scope.PopBlock();
 		}
 
-		public override void Compile(Execution.VM.Chunk bc)
+		public override void Compile(Execution.VM.ByteCode bc)
 		{
 			bc.Enter(m_StackFrame);
 			m_Block.Compile(bc);

+ 1 - 1
src/MoonSharp.Interpreter/Tree/Statements/WhileStatement.cs

@@ -25,7 +25,7 @@ namespace MoonSharp.Interpreter.Tree.Statements
 		}
 
 
-		public override void Compile(Chunk bc)
+		public override void Compile(ByteCode bc)
 		{
 			Loop L = new Loop()
 			{

+ 9 - 10
src/MoonSharp/Program.cs

@@ -11,17 +11,17 @@ namespace MoonSharp
 {
 	class Program
 	{
-		static RValue Print(IExecutionContext executionContext, CallbackArguments values)
+		static DynValue Print(IExecutionContext executionContext, CallbackArguments values)
 		{
-			string prn = string.Join(" ", values.List.Select(v => v.AsString()).ToArray());
+			string prn = string.Join(" ", values.List.Select(v => v.ToPrintString()).ToArray());
 			Console.WriteLine("{0}", prn);
-			return RValue.Nil;
+			return DynValue.Nil;
 		}
 
-		static RValue Read(IExecutionContext executionContext, CallbackArguments values)
+		static DynValue Read(IExecutionContext executionContext, CallbackArguments values)
 		{
 			double d = double.Parse(Console.ReadLine());
-			return new RValue(d);
+			return DynValue.NewNumber(d);
 		}
 
 		static StringBuilder g_TreeDump = new StringBuilder();
@@ -32,18 +32,17 @@ namespace MoonSharp
 			Console.WriteLine("Moon# {0}\nCopyright (C) 2014 Marco Mastropaolo\nhttp://www.moonsharp.org",
 				Assembly.GetExecutingAssembly().GetName().Version);
 
-			Console.WriteLine("Based on Lua 5.2, Copyright (C) 1994-2013 Lua.org");
+			Console.WriteLine("Based on Lua 5.1 - 5.3, Copyright (C) 1994-2014 Lua.org");
 
 			Console.WriteLine();
 
 			if (args.Length == 1)
 			{
-				Table globalTable = new Table();
-				globalTable[new RValue("print")] = new RValue(new CallbackFunction(Print));
+				Script script = new Script();
 
-				var script = MoonSharpInterpreter.LoadFromFile(args[0]);
+				script.Globals["print"] = DynValue.NewCallback(new CallbackFunction(Print));
 
-				script.Execute(globalTable);
+				script.DoFile(args[0]);
 
 				Console.WriteLine("Done.");
 				

+ 12 - 11
src/PerformanceComparison/Program.cs

@@ -86,25 +86,25 @@ end
 		static StringBuilder g_MoonSharpStr = new StringBuilder();
 		static StringBuilder g_NLuaStr = new StringBuilder();
 
-		public static RValue Print(IExecutionContext executionContext, CallbackArguments values)
+		public static DynValue Print(IExecutionContext executionContext, CallbackArguments values)
 		{
 			foreach (var val in values.List)
 			{
-				g_MoonSharpStr.Append(val.AsString());
+				g_MoonSharpStr.Append(val.ToPrintString());
 			}
 
 			g_MoonSharpStr.AppendLine();
-			return RValue.Nil;
+			return DynValue.Nil;
 		}
 
 		private static void Example()
 		{
 			Table t = new Table();
-			t[new RValue("print")] = new RValue(new CallbackFunction(Print));
+			t["print"] = DynValue.NewCallback(Print);
 
-			Script script = MoonSharpInterpreter.LoadFromFile(@"c:\temp\test.lua");
+			Script script = new Script(t);
 
-			RValue retVal = script.Execute(t);
+			DynValue retVal = script.DoFile("test.lua");
 		}
 
 		public static void NPrint(params object[] values)
@@ -126,9 +126,9 @@ end
 			sw = Stopwatch.StartNew();
 
 			Table t = new Table();
-			t[new RValue("print")] = new RValue(new CallbackFunction(Print));
+			t["print"] = DynValue.NewCallback(new CallbackFunction(Print));
 
-			MoonSharpInterpreter.LoadFromString(scriptText);
+			Script.RunString(scriptText);
 
 			sw.Stop();
 
@@ -137,9 +137,10 @@ end
 			sw = Stopwatch.StartNew();
 
 			t = new Table();
-			t[new RValue("print")] = new RValue(new CallbackFunction(Print));
+			t["print"] = DynValue.NewCallback(new CallbackFunction(Print));
 
-			var script = MoonSharpInterpreter.LoadFromString(scriptText);
+			var script = new Script(t);
+			DynValue func = script.LoadString(scriptText);
 
 			sw.Stop();
 
@@ -149,7 +150,7 @@ end
 			sw = Stopwatch.StartNew();
 			for (int i = 0; i < ITERATIONS; i++)
 			{
-				script.Execute(t);
+				script.Call(0, func);
 			}
 			sw.Stop();