Browse Source

new table definition

Xanathar 11 years ago
parent
commit
a11aaea969
26 changed files with 358 additions and 594 deletions
  1. 0 0
      src/MoonSharp.Interpreter.Tests/EndToEnd/ClosureTests.cs
  2. 0 0
      src/MoonSharp.Interpreter.Tests/EndToEnd/LuaTestSuiteExtract.cs
  3. 27 0
      src/MoonSharp.Interpreter.Tests/EndToEnd/SimpleTests.cs
  4. 0 0
      src/MoonSharp.Interpreter.Tests/EndToEnd/TableTests.cs
  5. 9 6
      src/MoonSharp.Interpreter.Tests/MoonSharp.Interpreter.Tests.csproj
  6. 0 0
      src/MoonSharp.Interpreter.Tests/TestMore/TapRunner.cs
  7. 0 0
      src/MoonSharp.Interpreter.Tests/TestMore/TestMoreTests.cs
  8. 16 0
      src/MoonSharp.Interpreter/CoreLib/CoreLibModule.cs
  9. 110 0
      src/MoonSharp.Interpreter/DataStructs/LinkedListIndex.cs
  10. 125 85
      src/MoonSharp.Interpreter/Execution/DataTypes/Table.cs
  11. 35 0
      src/MoonSharp.Interpreter/Execution/DataTypes/TablePair.cs
  12. 0 4
      src/MoonSharp.Interpreter/Execution/Scopes/BuildTimeScopeBlock.cs
  13. 0 128
      src/MoonSharp.Interpreter/Execution/Scopes/OldScopeClasses/BuildTimeScope.cs
  14. 0 56
      src/MoonSharp.Interpreter/Execution/Scopes/OldScopeClasses/BuildTimeScopeFrame.cs
  15. 0 196
      src/MoonSharp.Interpreter/Execution/Scopes/OldScopeClasses/RuntimeScope.cs
  16. 0 30
      src/MoonSharp.Interpreter/Execution/Scopes/OldScopeClasses/RuntimeScopeFrame.cs
  17. 1 0
      src/MoonSharp.Interpreter/Execution/VM/CallStackItem.cs
  18. 2 25
      src/MoonSharp.Interpreter/Execution/VM/Chunk.cs
  19. 4 0
      src/MoonSharp.Interpreter/Execution/VM/Instruction.cs
  20. 1 3
      src/MoonSharp.Interpreter/Execution/VM/OpCode.cs
  21. 0 1
      src/MoonSharp.Interpreter/Execution/VM/Processor/Processor.cs
  22. 8 10
      src/MoonSharp.Interpreter/Execution/VM/Processor/Processor_InstructionLoop.cs
  23. 13 40
      src/MoonSharp.Interpreter/Execution/VM/Processor/Processor_Scope.cs
  24. 3 4
      src/MoonSharp.Interpreter/MoonSharp.Interpreter.csproj
  25. 0 2
      src/MoonSharp.Interpreter/Tree/Expressions/FunctionDefinitionExpression.cs
  26. 4 4
      src/PerformanceComparison/Program.cs

+ 0 - 0
src/MoonSharp.Interpreter.Tests/ClosureTests.cs → src/MoonSharp.Interpreter.Tests/EndToEnd/ClosureTests.cs


+ 0 - 0
src/MoonSharp.Interpreter.Tests/LuaTestSuiteExtract.cs → src/MoonSharp.Interpreter.Tests/EndToEnd/LuaTestSuiteExtract.cs


+ 27 - 0
src/MoonSharp.Interpreter.Tests/SimpleTests.cs → src/MoonSharp.Interpreter.Tests/EndToEnd/SimpleTests.cs

@@ -704,5 +704,32 @@ namespace MoonSharp.Interpreter.Tests
 
 
 		}
 		}
 
 
+		[Test]
+		public void ArgsDoNotChange()
+		{
+			string script = @"
+					local a = 1;
+					local b = 2;
+
+					function x(c, d)
+						c = c + 3;
+						d = d + 4;
+						return c + d;
+					end
+
+					return x(a, b+1), a, b;
+								";
+
+			RValue res = MoonSharpInterpreter.LoadFromString(script).Execute(null);
+
+			Assert.AreEqual(3, res.Tuple.Length);
+			Assert.AreEqual(DataType.Number, res.Tuple[0].Type);
+			Assert.AreEqual(DataType.Number, res.Tuple[1].Type);
+			Assert.AreEqual(DataType.Number, res.Tuple[2].Type);
+			Assert.AreEqual(11, res.Tuple[0].Number);
+			Assert.AreEqual(1, res.Tuple[1].Number);
+			Assert.AreEqual(2, res.Tuple[2].Number);
+		}
+
 	}
 	}
 }
 }

+ 0 - 0
src/MoonSharp.Interpreter.Tests/TableTests.cs → src/MoonSharp.Interpreter.Tests/EndToEnd/TableTests.cs


+ 9 - 6
src/MoonSharp.Interpreter.Tests/MoonSharp.Interpreter.Tests.csproj

@@ -72,13 +72,13 @@
     <Otherwise />
     <Otherwise />
   </Choose>
   </Choose>
   <ItemGroup>
   <ItemGroup>
-    <Compile Include="ClosureTests.cs" />
-    <Compile Include="LuaTestSuiteExtract.cs" />
+    <Compile Include="EndToEnd\ClosureTests.cs" />
+    <Compile Include="EndToEnd\LuaTestSuiteExtract.cs" />
     <Compile Include="Properties\AssemblyInfo.cs" />
     <Compile Include="Properties\AssemblyInfo.cs" />
-    <Compile Include="SimpleTests.cs" />
-    <Compile Include="TableTests.cs" />
-    <Compile Include="TapRunner.cs" />
-    <Compile Include="TestMoreTests.cs" />
+    <Compile Include="EndToEnd\SimpleTests.cs" />
+    <Compile Include="EndToEnd\TableTests.cs" />
+    <Compile Include="TestMore\TapRunner.cs" />
+    <Compile Include="TestMore\TestMoreTests.cs" />
   </ItemGroup>
   </ItemGroup>
   <ItemGroup>
   <ItemGroup>
     <ProjectReference Include="..\MoonSharp.Interpreter\MoonSharp.Interpreter.csproj">
     <ProjectReference Include="..\MoonSharp.Interpreter\MoonSharp.Interpreter.csproj">
@@ -218,6 +218,9 @@
       <CopyToOutputDirectory>Always</CopyToOutputDirectory>
       <CopyToOutputDirectory>Always</CopyToOutputDirectory>
     </Content>
     </Content>
   </ItemGroup>
   </ItemGroup>
+  <ItemGroup>
+    <Folder Include="Units\" />
+  </ItemGroup>
   <Choose>
   <Choose>
     <When Condition="'$(VisualStudioVersion)' == '10.0' And '$(IsCodedUITest)' == 'True'">
     <When Condition="'$(VisualStudioVersion)' == '10.0' And '$(IsCodedUITest)' == 'True'">
       <ItemGroup>
       <ItemGroup>

+ 0 - 0
src/MoonSharp.Interpreter.Tests/TapRunner.cs → src/MoonSharp.Interpreter.Tests/TestMore/TapRunner.cs


+ 0 - 0
src/MoonSharp.Interpreter.Tests/TestMoreTests.cs → src/MoonSharp.Interpreter.Tests/TestMore/TestMoreTests.cs


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

@@ -0,0 +1,16 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+
+namespace MoonSharp.Interpreter.CoreLib
+{
+	public enum CoreLibModule
+	{
+		TableIterators,
+		Metatables,
+
+
+
+	}
+}

+ 110 - 0
src/MoonSharp.Interpreter/DataStructs/LinkedListIndex.cs

@@ -0,0 +1,110 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+
+namespace MoonSharp.Interpreter.DataStructs
+{
+	/// <summary>
+	/// An index to accelerate operations on a LinkedList<typeparamref name="TValue"/> using a single key of type <typeparamref name="TKey"/>
+	/// More than one LinkedListIndex can index the same linked list, but every node in the linked list must be indexed by one and only one
+	/// LinkedListIndex object.
+	/// </summary>
+	/// <typeparam name="TKey">The type of the key. Must implement Equals and GetHashCode appropriately.</typeparam>
+	/// <typeparam name="TValue">The type of the values contained in the linked list.</typeparam>
+	public class LinkedListIndex<TKey, TValue>
+	{
+		LinkedList<TValue> m_LinkedList;
+		Dictionary<TKey, LinkedListNode<TValue>> m_Map = null;
+
+		/// <summary>
+		/// Initializes a new instance of the <see cref="LinkedListIndex{TKey, TValue}"/> class.
+		/// </summary>
+		/// <param name="linkedList">The linked list to be indexed.</param>
+		public LinkedListIndex(LinkedList<TValue> linkedList)
+		{
+			m_LinkedList = linkedList;
+		}
+
+		/// <summary>
+		/// Finds the node indexed by the specified key, or null.
+		/// </summary>
+		/// <param name="key">The key.</param>
+		public LinkedListNode<TValue> Find(TKey key)
+		{
+			LinkedListNode<TValue> node;
+
+			if (m_Map == null)
+				return null;
+
+			if (m_Map.TryGetValue(key, out node))
+				return node;
+
+			return null;
+		}
+
+		/// <summary>
+		/// Updates or creates a new node in the linked list, indexed by the specified key.
+		/// </summary>
+		/// <param name="key">The key.</param>
+		/// <param name="value">The value.</param>
+		/// <returns>True if the value has been created</returns>
+		public bool Set(TKey key, TValue value)
+		{
+			LinkedListNode<TValue> node = Find(key);
+
+			if (node == null)
+			{
+				Add(key, value);
+				return true;
+			}
+			else
+			{
+				node.Value = value;
+				return false;
+			}
+		}
+
+		/// <summary>
+		/// Creates a new node in the linked list, indexed by the specified key.
+		/// </summary>
+		/// <param name="key">The key.</param>
+		/// <param name="value">The value.</param>
+		public void Add(TKey key, TValue value)
+		{
+			var node = m_LinkedList.AddLast(value);
+
+			if (m_Map == null)
+				m_Map = new Dictionary<TKey, LinkedListNode<TValue>>();
+
+			m_Map.Add(key, node);
+		}
+
+		/// <summary>
+		/// Removes the specified key from the index, and the node indexed by the key from the linked list.
+		/// </summary>
+		/// <param name="key">The key.</param>
+		public void Remove(TKey key)
+		{
+			LinkedListNode<TValue> node = Find(key);
+
+			if (node != null)
+			{
+				m_LinkedList.Remove(node);
+				m_Map.Remove(key);
+			}
+		}
+
+		/// <summary>
+		/// Determines whether the index contains the specified key.
+		/// </summary>
+		/// <param name="key">The key.</param>
+		public bool ContainsKey(TKey key)
+		{
+			if (m_Map == null)
+				return false;
+
+			return m_Map.ContainsKey(key);
+		}
+	}
+}

+ 125 - 85
src/MoonSharp.Interpreter/Execution/DataTypes/Table.cs

@@ -2,157 +2,197 @@
 using System.Collections.Generic;
 using System.Collections.Generic;
 using System.Linq;
 using System.Linq;
 using System.Text;
 using System.Text;
+using MoonSharp.Interpreter.DataStructs;
+using MoonSharp.Interpreter.Execution.DataTypes;
 
 
 namespace MoonSharp.Interpreter.Execution
 namespace MoonSharp.Interpreter.Execution
 {
 {
 	public class Table
 	public class Table
 	{
 	{
-		Dictionary<RValue, RValue> m_Symbols = new Dictionary<RValue, RValue>();
-		Dictionary<string, RValue> m_StringSymbols = new Dictionary<string, RValue>();
-		int m_LastConsecutiveInteger = 0;
-		int m_MaxInteger = 0;
+		LinkedList<TablePair> m_Values;
+		LinkedListIndex<RValue, TablePair> m_ValueMap;
+		LinkedListIndex<string, TablePair> m_StringMap;
+		LinkedListIndex<int, TablePair> m_ArrayMap;
 
 
+		int m_CachedLength = -1;
 
 
-		private void RebuildArrayIndex()
+		public Table()
 		{
 		{
-			var numberKeys = m_Symbols.Keys
-				.Where(t => t.Type == DataType.Number)
-				.Select(t => t.Number)
-				.OrderBy(t => t);
-
-			m_LastConsecutiveInteger = m_MaxInteger = 0;
-
-			foreach (double key in numberKeys)
-			{
-				UpdateIntegersOnAdd(key);
-			}
+			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);
 		}
 		}
 
 
-		private void UpdateIntegersOnAdd(double key)
+		private int GetIntegralKey(double d)
 		{
 		{
-			int ikey = (int)key;
-
-			if (ikey != key || ikey <= 0)
-				return;
+			int v = ((int)d);
 
 
-			if (ikey == m_LastConsecutiveInteger + 1)
-				m_LastConsecutiveInteger = ikey;
+			if (d >= 1.0 && d == v)
+				return v;
 
 
-			if (m_MaxInteger > ikey)
-
-			m_MaxInteger = Math.Max(m_MaxInteger, ikey);
+			return -1;
 		}
 		}
 
 
-
 		public RValue this[RValue key]
 		public RValue this[RValue key]
 		{
 		{
-			get { return GetSymbol(key); }
+			get 
+			{
+				if (key.Type == DataType.Number)
+				{
+					int idx = GetIntegralKey(key.Number);
+					if (idx > 0)
+					{
+						return GetValueOrNil(m_ArrayMap.Find(idx));
+					}
+				}
+				else if (key.Type == DataType.String)
+				{
+					return GetValueOrNil(m_StringMap.Find(key.String));
+				}
+
+				return GetValueOrNil(m_ValueMap.Find(key));
+			}
 			set 
 			set 
 			{
 			{
+				if (key.Type == DataType.String)
+				{
+					this[key.String] = value;
+					return;
+				}
+
+				if (key.Type == DataType.Number)
+				{
+					int idx = GetIntegralKey(key.Number);
+
+					if (idx > 0)
+					{
+						this[idx] = value;
+						return;
+					}
+				}
+				
 				if (value.Type == DataType.Nil)
 				if (value.Type == DataType.Nil)
 				{
 				{
-					Remove(key);
+					m_ValueMap.Remove(key);
+					m_CachedLength = -1;
 				}
 				}
 				else
 				else
 				{
 				{
-					Set(key, value);
+					if (m_ValueMap.Set(key, new TablePair(key, value)))
+						m_CachedLength = -1;
 				}
 				}
 			}
 			}
 		}
 		}
 
 
-		public IEnumerable<KeyValuePair<RValue, RValue>> DebugPairs()
+		private RValue GetValueOrNil(LinkedListNode<TablePair> linkedListNode)
 		{
 		{
-			foreach (var kvp in m_Symbols)
-				yield return kvp;
+			if (linkedListNode != null)
+				return linkedListNode.Value.Value;
 
 
-			foreach (var kvp in m_StringSymbols)
-				yield return new KeyValuePair<RValue, RValue>(new RValue(kvp.Key), kvp.Value);
+			return RValue.Nil;
 		}
 		}
 
 
-		private void Remove(RValue key)
+		public RValue this[string key]
 		{
 		{
-			if (key.Type == DataType.String)
+			get
 			{
 			{
-				m_StringSymbols.Remove(key.String);
+				return GetValueOrNil(m_StringMap.Find(key));
 			}
 			}
-			else
+			set
 			{
 			{
-				m_Symbols.Remove(key);
-
-				if (key.Type == DataType.Number)
-					RebuildArrayIndex(); // TODO: Optimize
+				if (value.Type == DataType.Nil)
+				{
+					m_StringMap.Remove(key);
+				}
+				else
+				{
+					m_StringMap.Set(key, new TablePair(new RValue(key), value));
+				}
 			}
 			}
 		}
 		}
 
 
-		public void Set(RValue key, RValue value)
+		public RValue this[int key]
 		{
 		{
-			if (key.Type == DataType.String)
+			get
 			{
 			{
-				m_StringSymbols[key.String] = value.CloneAsWritable();
+				return GetValueOrNil(m_ArrayMap.Find(key));
 			}
 			}
-			else
+			set
 			{
 			{
-				m_Symbols[key.Clone()] = value.CloneAsWritable();
-
-				if (key.Type == DataType.Number)
-					RebuildArrayIndex(); // TODO: Optimize
+				if (value.Type == DataType.Nil)
+				{
+					m_ArrayMap.Remove(key);
+				}
+				else
+				{
+					m_ArrayMap.Set(key, new TablePair(new RValue(key), value));
+				}
 			}
 			}
 		}
 		}
 
 
-		public bool HasStringSymbol(string symbol)
+		public IEnumerable<TablePair> DebugPairs()
 		{
 		{
-			return m_StringSymbols.ContainsKey(symbol);
+			return m_Values;
 		}
 		}
 
 
-
-		public RValue this[string key]
+		public TablePair NextKey(RValue v)
 		{
 		{
-			get 
+			if (v.Type == DataType.Nil)
 			{
 			{
-				RValue v;
+				LinkedListNode<TablePair> node = m_Values.First;
 
 
-				if (m_StringSymbols.TryGetValue(key, out v))
-					return v;
+				if (node == null)
+					return TablePair.Nil;
+				else
+					return node.Value;
+			}
 
 
-				return RValue.Nil;
+			if (v.Type == DataType.String)
+			{
+				return GetNextOf(m_StringMap.Find(v.String));
 			}
 			}
-			set
+
+			if (v.Type == DataType.Number)
 			{
 			{
-				if (value.Type == DataType.Nil)
-				{
-					m_StringSymbols.Remove(key);
-				}
-				else
+				int idx = GetIntegralKey(v.Number);
+
+				if (idx > 0)
 				{
 				{
-					m_StringSymbols[key] = value;
+					return GetNextOf(m_ArrayMap.Find(idx));
 				}
 				}
 			}
 			}
-		}
-
-
-
-
 
 
+			return GetNextOf(m_ValueMap.Find(v));
+		}
 
 
-		public RValue GetSymbol(RValue key)
+		private TablePair GetNextOf(LinkedListNode<TablePair> linkedListNode)
 		{
 		{
-			if (key.Type == DataType.String)
-			{
-				if (m_StringSymbols.ContainsKey(key.String))
-					return m_StringSymbols[key.String];
-			}
-			else
-			{
-				if (m_Symbols.ContainsKey(key))
-					return m_Symbols[key];
-			}
+			if (linkedListNode == null)
+				return TablePair.Nil;
 
 
-			return RValue.Nil;
+			return linkedListNode.Next.Value;
+		}
+		
+		public bool HasStringSymbol(string symbol)
+		{
+			return m_StringMap.ContainsKey(symbol);
 		}
 		}
 
 
 		public double Length
 		public double Length
 		{
 		{
-			get { return m_LastConsecutiveInteger; }
+			get 
+			{
+				if (m_CachedLength < 0)
+				{
+					m_CachedLength = 0;
+
+					for (int i = 1; m_ArrayMap.ContainsKey(i); i++)
+						m_CachedLength = i;
+				}
+
+				return m_CachedLength; 
+			}
 		}
 		}
 
 
 
 

+ 35 - 0
src/MoonSharp.Interpreter/Execution/DataTypes/TablePair.cs

@@ -0,0 +1,35 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+
+namespace MoonSharp.Interpreter.Execution.DataTypes
+{
+	public struct TablePair
+	{
+		private static TablePair s_NilNode = new TablePair(RValue.Nil, RValue.Nil);
+
+		private RValue key, value;
+
+		public RValue Key 
+		{
+			get { return key; }
+			private set { Key = key; }
+		}
+
+		public RValue Value
+		{
+			get { return value; }
+			set { if (key.Type != DataType.Nil) Value = value; }
+		}
+
+
+		public TablePair(RValue key, RValue val) 
+		{
+			this.key = key;
+			this.value = val;
+		}
+
+		public static TablePair Nil { get { return s_NilNode; } }
+	}
+}

+ 0 - 4
src/MoonSharp.Interpreter/Execution/Scopes/BuildTimeScopeBlock.cs

@@ -37,10 +37,6 @@ namespace MoonSharp.Interpreter.Execution.Scopes
 		internal LRef Define(string name)
 		internal LRef Define(string name)
 		{
 		{
 			LRef l = LRef.Local(name, -1);
 			LRef l = LRef.Local(name, -1);
-			if (m_DefinedNames.ContainsKey(name))
-			{
-				int a = 3;
-			}
 			m_DefinedNames.Add(name, l);
 			m_DefinedNames.Add(name, l);
 			return l;
 			return l;
 		}
 		}

+ 0 - 128
src/MoonSharp.Interpreter/Execution/Scopes/OldScopeClasses/BuildTimeScope.cs

@@ -1,128 +0,0 @@
-using System;
-using System.Collections.Generic;
-using MoonSharp.Interpreter.Diagnostics;
-using System.Linq;
-using System.Text;
-
-namespace MoonSharp.Interpreter.Execution
-{
-	public class BuildTimeScope_UNUSED
-	{
-		List<BuildTimeScopeFrame_UNUSED> m_Locals = new List<BuildTimeScopeFrame_UNUSED>();
-		List<IClosureBuilder> m_ClosureBuilders = new List<IClosureBuilder>();
-
-		public BuildTimeScope_UNUSED()
-		{
-			PushFunction();
-		}
-
-		public void EnterClosure(IClosureBuilder closureBuilder)
-		{
-			m_ClosureBuilders.Add(closureBuilder);
-			closureBuilder.UpvalueCreationTag = (m_Locals.Count - 1);
-		}
-
-		public void LeaveClosure()
-		{
-			m_ClosureBuilders.RemoveAt(m_ClosureBuilders.Count - 1);
-		}
-
-
-		int GetStartIndexForPush()
-		{
-			return m_Locals[m_Locals.Count - 1].MaxIndex;
-		}
-		int GetBaseIndexForPush()
-		{
-			return m_Locals[m_Locals.Count - 1].BaseIndex;
-		}
-
-		public void PushBlock()
-		{
-			// Debug.WriteLine("PushBlock");
-			m_Locals.Add(new BuildTimeScopeFrame_UNUSED(GetBaseIndexForPush(), GetStartIndexForPush(), false));
-		}
-
-		public void PushFunction()
-		{
-			// Debug.WriteLine("PushFunction");
-			m_Locals.Add(new BuildTimeScopeFrame_UNUSED(0, 0, true));
-		}
-
-		RuntimeScopeFrame_UNUSED GetRuntimeFrameFromBuildFrame(BuildTimeScopeFrame_UNUSED frame, bool local)
-		{
-			List<LRef> symbols = new List<LRef>();
-			for (int i = frame.StartIndex; i < frame.MaxIndex; i++)
-			{
-				LRef s;
-				if (local)
-					s = LRef.Local(frame.FindRev(i - frame.BaseIndex), i - frame.BaseIndex);
-				else
-					s = LRef.Global(frame.FindRev(i - frame.BaseIndex));
-
-				symbols.Add(s);
-			}
-
-			return new RuntimeScopeFrame_UNUSED(symbols, frame.MaxIndex - frame.StartIndex, frame.Breaking);
-		}
-
-		public RuntimeScopeFrame_UNUSED Pop()
-		{
-			BuildTimeScopeFrame_UNUSED frame = m_Locals[m_Locals.Count - 1];
-			m_Locals.RemoveAt(m_Locals.Count - 1);
-			// Debug.WriteLine(string.Format("Pop : {0}", frame.MaxIndex - frame.StartIndex));
-
-			return GetRuntimeFrameFromBuildFrame(frame, true);
-		}
-
-		public LRef Find(string name)
-		{
-			for (int i = m_Locals.Count - 1; i >= 0; i--)
-			{
-				int idx = m_Locals[i].Find(name);
-				if (idx >= 0)
-					return LRef.Local(name, idx);
-
-				if (m_Locals[i].Breaking)
-					break;
-			}
-
-			IClosureBuilder closure = m_ClosureBuilders.LastOrDefault();
-
-			if (closure != null)
-			{
-				int closureLocalBlockIdx = (int)closure.UpvalueCreationTag;
-
-				if (closureLocalBlockIdx >= 0)
-				{
-					for (int i = closureLocalBlockIdx; i >= 0; i--)
-					{
-						int idx = m_Locals[i].Find(name);
-						if (idx >= 0)
-							return null; // was closure.CreateUpvalue(this, LRef.Local(name, idx));
-					}
-				}
-			}
-
-			return LRef.Global(name);
-		}
-
-		public LRef DefineLocal(string name)
-		{
-			return LRef.Local(name, m_Locals[m_Locals.Count - 1].Define(name));
-		}
-
-		public LRef TryDefineLocal(string name)
-		{
-			int idx = m_Locals[m_Locals.Count - 1].Find(name);
-
-			if (idx >= 0)
-				return LRef.Local(name, idx);
-
-			var s = LRef.Local(name, m_Locals[m_Locals.Count - 1].Define(name));
-			// Debug.WriteLine(string.Format("Define local : {0}", s));
-			return s;
-		}
-
-	}
-}

+ 0 - 56
src/MoonSharp.Interpreter/Execution/Scopes/OldScopeClasses/BuildTimeScopeFrame.cs

@@ -1,56 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using MoonSharp.Interpreter.Execution;
-
-namespace MoonSharp.Interpreter.Execution
-{
-	class BuildTimeScopeFrame_UNUSED
-	{
-		Dictionary<string, int> m_IndexList = new Dictionary<string, int>();
-		Dictionary<int, string> m_RevIndexList = new Dictionary<int, string>();
-
-		public int BaseIndex { get; private set; }
-		public int StartIndex { get; private set; }
-
-		public int MaxIndex { get; private set; }
-
-		public bool Breaking { get; private set; }
-
-		public BuildTimeScopeFrame_UNUSED(int baseIndex, int startIndex, bool breaking)
-		{
-			BaseIndex = baseIndex;
-			StartIndex = MaxIndex = startIndex;
-			Breaking = breaking;
-		}
-
-		public int Find(string name)
-		{
-			if (m_IndexList.ContainsKey(name))
-				return m_IndexList[name];
-
-			return -1;
-		}
-
-		public string FindRev(int idx)
-		{
-			return m_RevIndexList[idx];
-		}
-
-		public int Define(string name)
-		{
-			if (!m_IndexList.ContainsKey(name))
-			{
-				m_IndexList.Add(name, MaxIndex - BaseIndex);
-				m_RevIndexList.Add(MaxIndex - BaseIndex, name);
-				return MaxIndex++;
-			}
-			else
-			{
-				return m_IndexList[name];
-			}
-		}
-
-	}
-}

+ 0 - 196
src/MoonSharp.Interpreter/Execution/Scopes/OldScopeClasses/RuntimeScope.cs

@@ -1,196 +0,0 @@
-using System;
-using System.Collections.Generic;
-using MoonSharp.Interpreter.Diagnostics;
-using System.Linq;
-using System.Text;
-using MoonSharp.Interpreter.Execution.VM;
-using MoonSharp.Interpreter.DataStructs;
-
-namespace MoonSharp.Interpreter.Execution
-{
-	public class RuntimeScope_UNUSED
-	{
-		Table m_GlobalTable;
-		FastStack<RValue> m_ScopeStack = new FastStack<RValue>(131072); // start with a 512KB scope stack
-		FastStack<int> m_LocalBaseIndexes = new FastStack<int>(16384);
-		FastStack<ClosureContext> m_ClosureStack = new FastStack<ClosureContext>(4096);
-		FastStack<RuntimeScopeFrame_UNUSED> m_ScopeFrames = new FastStack<RuntimeScopeFrame_UNUSED>(8192);
-
-		public RuntimeScope_UNUSED()
-		{
-		}
-
-		public Table GlobalTable
-		{
-			get { return m_GlobalTable; }
-			set { m_GlobalTable = value; }
-		}
-
-		public void EnterClosure(ClosureContext closureValues)
-		{
-			m_ClosureStack.Push(closureValues);
-		}
-
-		public void LeaveClosure()
-		{
-			m_ClosureStack.RemoveLast();
-		}
-
-		public void PushFrame(RuntimeScopeFrame_UNUSED frame)
-		{
-			int size = frame.Count;
-
-			m_ScopeFrames.Push(frame);
-
-			if (frame.RestartOfBase)
-				m_LocalBaseIndexes.Push(m_ScopeStack.Count);
-
-			m_ScopeStack.Expand(size);
-
-		}
-
-		public void PopFrame(RuntimeScopeFrame_UNUSED frame)
-		{
-			System.Diagnostics.Debug.Assert(frame == m_ScopeFrames.Peek());
-			PopFrame();
-		}
-
-
-		public RuntimeScopeFrame_UNUSED PopFrame()
-		{
-			RuntimeScopeFrame_UNUSED frame = m_ScopeFrames.Pop();
-
-			int size = frame.Count;
-			if (size > 0)
-			{
-				m_ScopeStack.RemoveLast(size);
-			}
-
-			if (frame.RestartOfBase)
-			{
-				m_LocalBaseIndexes.RemoveLast();
-			}
-			return frame;
-		}
-
-		public void PopFramesToFunction()
-		{
-			while (!PopFrame().RestartOfBase) ;
-		}
-
-		public void PopFramesToFrame(RuntimeScopeFrame_UNUSED runtimeScopeFrame)
-		{
-			while (m_ScopeFrames.Peek() != runtimeScopeFrame)
-				PopFrame();
-		}
-
-		public RValue Get(LRef symref)
-		{
-			switch (symref.i_Type)
-			{
-				case LRefType.Global:
-					{
-						return m_GlobalTable[symref.i_Name];
-					}
-				case LRefType.Local:
-					{
-						int lastBaseIdx = m_LocalBaseIndexes[m_LocalBaseIndexes.Count - 1];
-						var v = m_ScopeStack[lastBaseIdx + symref.i_Index];
-						if (v == null)
-							m_ScopeStack[lastBaseIdx + symref.i_Index] = v = new RValue();
-						return v;
-					}
-				case LRefType.Upvalue:
-					{
-						List<RValue> closureValues = m_ClosureStack.Count > 0 ? m_ClosureStack[m_ClosureStack.Count - 1] : null;
-
-						if (closureValues != null)
-						{
-							return closureValues[symref.i_Index];
-						}
-						else
-						{
-							throw new ScriptRuntimeException(null, "Invalid upvalue at resolution: {0}", symref.i_Name);
-						}
-					}
-				case LRefType.Invalid:
-				default:
-					{
-						throw new ScriptRuntimeException(null, "Invalid value at resolution: {0}", symref.i_Name);
-					}
-			}
-		}
-
-
-		public void Assign(LRef symref, RValue value)
-		{
-			switch (symref.i_Type)
-			{
-				case LRefType.Global:
-					{
-						m_GlobalTable[symref.i_Name] = value.CloneAsWritable();
-					}
-					break;
-				case LRefType.Local:
-					{
-						int lastBaseIdx = m_LocalBaseIndexes[m_LocalBaseIndexes.Count - 1];
-						RValue v = m_ScopeStack[lastBaseIdx + symref.i_Index];
-						if (v == null)
-							m_ScopeStack[lastBaseIdx + symref.i_Index] = v = new RValue();
-						v.Assign(value);
-					}
-					break;
-				case LRefType.Upvalue:
-					{
-						List<RValue> closureValues = m_ClosureStack.Count > 0 ? m_ClosureStack[m_ClosureStack.Count - 1] : null;
-
-						if (closureValues != null)
-						{
-							closureValues[symref.i_Index].Assign(value);
-						}
-						else
-						{
-							throw new ScriptRuntimeException(null, "Invalid upvalue at resolution: {0}", symref.i_Name);
-						}
-					}
-					break;
-				case LRefType.Invalid:
-				default:
-					{
-						throw new ScriptRuntimeException(null, "Invalid value at resolution: {0}", symref.i_Name);
-					}
-			}
-		}
-
-		public LRef FindRefByName(string name)
-		{
-			for(int i = m_ScopeFrames.Count - 1; i >= 0; i--)
-			{
-				var frame = m_ScopeFrames[i];
-				
-				foreach(LRef l in frame.m_DebugSymbols)
-					if (l.i_Name == name)
-						return l;
-			
-				if (frame.RestartOfBase)
-					break;
-			}
-
-			if (m_ClosureStack.Count > 0)
-			{
-				var closure = m_ClosureStack.Peek(0);
-
-				for(int i = 0; i < closure.Symbols.Length; i++)
-					if (closure.Symbols[i] == name)
-					{
-						return LRef.Upvalue(name, i);
-					}
-			}
-
-			if (m_GlobalTable.HasStringSymbol(name))
-				return LRef.Global(name);
-
-			return null;
-		}
-	}
-}

+ 0 - 30
src/MoonSharp.Interpreter/Execution/Scopes/OldScopeClasses/RuntimeScopeFrame.cs

@@ -1,30 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-
-namespace MoonSharp.Interpreter.Execution
-{
-	public class RuntimeScopeFrame_UNUSED
-	{
-		public List<LRef> m_DebugSymbols { get; private set;}
-		public int Count { get; private set;}
-		public bool RestartOfBase { get; private set; }
-
-
-		public RuntimeScopeFrame_UNUSED(IEnumerable<LRef> symbols, int count, bool restartOfBase)
-		{
-			m_DebugSymbols = symbols.ToList();
-			Count = count;
-			RestartOfBase = restartOfBase;
-
-			if (Count != m_DebugSymbols.Count)
-				throw new Exception("WTF");
-		}
-
-		public override string ToString()
-		{
-			return string.Format("{0} frame : #{1}", RestartOfBase ? "Function" : "Block", Count);
-		}
-	}
-}

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

@@ -13,6 +13,7 @@ namespace MoonSharp.Interpreter.Execution.VM
 		public int BasePointer;
 		public int BasePointer;
 		public int ReturnAddress;
 		public int ReturnAddress;
 		public RValue[] LocalScope;
 		public RValue[] LocalScope;
+		public ClosureContext ClosureScope;
 	}
 	}
 
 
 }
 }

+ 2 - 25
src/MoonSharp.Interpreter/Execution/VM/Chunk.cs

@@ -21,16 +21,6 @@ namespace MoonSharp.Interpreter.Execution.VM
 
 
 		public int ReferenceID { get { return m_RefID; } }
 		public int ReferenceID { get { return m_RefID; } }
 
 
-		private void TrackLoopStart()
-		{
-
-		}
-
-		private void TrackLoopEnd()
-		{
-
-		}
-
 
 
 		public void Dump(string file)
 		public void Dump(string file)
 		{
 		{
@@ -122,10 +112,6 @@ namespace MoonSharp.Interpreter.Execution.VM
 			return Emit(new Instruction() { OpCode = opcode });
 			return Emit(new Instruction() { OpCode = opcode });
 		}
 		}
 
 
-		public Instruction Bool()
-		{
-			return Emit(new Instruction() { OpCode = OpCode.Bool });
-		}
 
 
 		//[Conditional("EMIT_DEBUG_OPS")]
 		//[Conditional("EMIT_DEBUG_OPS")]
 		public void Debug(string str)
 		public void Debug(string str)
@@ -150,7 +136,7 @@ namespace MoonSharp.Interpreter.Execution.VM
 			return Emit(new Instruction() { OpCode = OpCode.Leave, Block = runtimeScopeBlock });
 			return Emit(new Instruction() { OpCode = OpCode.Leave, Block = runtimeScopeBlock });
 		}
 		}
 
 
-		public Instruction Exit(RuntimeScopeBlock runtimeScopeBlock = null)
+		public Instruction Exit(RuntimeScopeBlock runtimeScopeBlock)
 		{
 		{
 			return Emit(new Instruction() { OpCode = OpCode.Exit, Block = runtimeScopeBlock });
 			return Emit(new Instruction() { OpCode = OpCode.Exit, Block = runtimeScopeBlock });
 		}
 		}
@@ -165,11 +151,6 @@ namespace MoonSharp.Interpreter.Execution.VM
 			return Emit(new Instruction() { OpCode = OpCode.Args, SymbolList = symbols });
 			return Emit(new Instruction() { OpCode = OpCode.Args, SymbolList = symbols });
 		}
 		}
 
 
-		public Instruction ExitClsr()
-		{
-			return Emit(new Instruction() { OpCode = OpCode.ExitClsr });
-		}
-
 		public Instruction Ret(int retvals)
 		public Instruction Ret(int retvals)
 		{
 		{
 			return Emit(new Instruction() { OpCode = OpCode.Ret, NumVal = retvals });
 			return Emit(new Instruction() { OpCode = OpCode.Ret, NumVal = retvals });
@@ -199,6 +180,7 @@ namespace MoonSharp.Interpreter.Execution.VM
 		{
 		{
 			return Emit(new Instruction() { OpCode = OpCode.IndexRef });
 			return Emit(new Instruction() { OpCode = OpCode.IndexRef });
 		}
 		}
+
 		public Instruction IndexRefN()
 		public Instruction IndexRefN()
 		{
 		{
 			return Emit(new Instruction() { OpCode = OpCode.IndexRefN });
 			return Emit(new Instruction() { OpCode = OpCode.IndexRefN });
@@ -209,11 +191,6 @@ namespace MoonSharp.Interpreter.Execution.VM
 			return Emit(new Instruction() { OpCode = OpCode.NewTable });
 			return Emit(new Instruction() { OpCode = OpCode.NewTable });
 		}
 		}
 
 
-		public Instruction TempOp(OpCode opCode, int regNum)
-		{
-			return Emit(new Instruction() { OpCode = opCode, NumVal = regNum });
-		}
-
 		public Instruction IterPrep()
 		public Instruction IterPrep()
 		{
 		{
 			return Emit(new Instruction() { OpCode = OpCode.IterPrep });
 			return Emit(new Instruction() { OpCode = OpCode.IterPrep });

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

@@ -30,6 +30,7 @@ namespace MoonSharp.Interpreter.Execution.VM
 					append = string.Format("{0}({1})", GenSpaces(), string.Join(",", SymbolList.Select(s => s.ToString()).ToArray()));
 					append = string.Format("{0}({1})", GenSpaces(), string.Join(",", SymbolList.Select(s => s.ToString()).ToArray()));
 					break;
 					break;
 				case OpCode.Enter:
 				case OpCode.Enter:
+				case OpCode.Leave:
 				case OpCode.Exit:
 				case OpCode.Exit:
 					append = string.Format("{0}{1}", GenSpaces(), FrameToString(Block));
 					append = string.Format("{0}{1}", GenSpaces(), FrameToString(Block));
 					break;
 					break;
@@ -54,6 +55,9 @@ namespace MoonSharp.Interpreter.Execution.VM
 				case OpCode.Pop:
 				case OpCode.Pop:
 					append = string.Format("{0}{1}", GenSpaces(), NumVal);
 					append = string.Format("{0}{1}", GenSpaces(), NumVal);
 					break;
 					break;
+				case OpCode.BeginFn:
+					append = string.Format("{0}{1}:{2},{3}", GenSpaces(), Name, NumVal, NumVal2);
+					break;
 				case OpCode.JtOrPop:
 				case OpCode.JtOrPop:
 				case OpCode.JfOrPop:
 				case OpCode.JfOrPop:
 				case OpCode.Jf:
 				case OpCode.Jf:

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

@@ -27,7 +27,6 @@ namespace MoonSharp.Interpreter.Execution.VM
 		Enter,		// Enters a new stack frame
 		Enter,		// Enters a new stack frame
 		Leave,		// Leaves a stack frame
 		Leave,		// Leaves a stack frame
 		Exit,		// Leaves every stack frame up and including the topmost function frame, plus it exits the topmost closure
 		Exit,		// Leaves every stack frame up and including the topmost function frame, plus it exits the topmost closure
-		ExitClsr,	// Exits a closure at runtime
 		BeginFn,	// Adjusts for start of function, taking in parameters and allocating locals
 		BeginFn,	// Adjusts for start of function, taking in parameters and allocating locals
 		Args,		// Takes the arguments passed to a function and sets the appropriate symbols in the local scope
 		Args,		// Takes the arguments passed to a function and sets the appropriate symbols in the local scope
 		Call,		// Calls the function specified on the specified element from the top of the v-stack. If the function is a Moon# function, it pushes its numeric value on the v-stack, then pushes the current PC onto the x-stack, enters the function closure and jumps to the function first instruction. If the function is a CLR function, it pops the function value from the v-stack, then invokes the function synchronously and finally pushes the result on the v-stack.
 		Call,		// Calls the function specified on the specified element from the top of the v-stack. If the function is a Moon# function, it pushes its numeric value on the v-stack, then pushes the current PC onto the x-stack, enters the function closure and jumps to the function first instruction. If the function is a CLR function, it pops the function value from the v-stack, then invokes the function synchronously and finally pushes the result on the v-stack.
@@ -58,7 +57,6 @@ namespace MoonSharp.Interpreter.Execution.VM
 
 
 		// Type conversions and manipulations
 		// Type conversions and manipulations
 		MkTuple,	// Creates a tuple from the topmost n values
 		MkTuple,	// Creates a tuple from the topmost n values
-		Bool,		// Converts the top of the v-stack to a boolean
 		Incr,		// Performs an add operation, without extracting the operands from the v-stack and assuming the operands are numbers.
 		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
 		ToNum,		// Converts the top of the stack to a number
 		ExpTuple,	// Expands a tuple on the stack
 		ExpTuple,	// Expands a tuple on the stack
@@ -71,7 +69,7 @@ namespace MoonSharp.Interpreter.Execution.VM
 		NewTable,	// Creates a new table on the stack
 		NewTable,	// Creates a new table on the stack
 
 
 		// Iterators
 		// Iterators
-		IterPrep,   // Prepares an interator for execution 
+		IterPrep,   // Prepares an iterator for execution 
 		IterUpd,	// Updates the var part of an iterator
 		IterUpd,	// Updates the var part of an iterator
 	}
 	}
 }
 }

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

@@ -16,7 +16,6 @@ namespace MoonSharp.Interpreter.Execution.VM
 
 
 		FastStack<RValue> m_ValueStack = new FastStack<RValue>(131072);
 		FastStack<RValue> m_ValueStack = new FastStack<RValue>(131072);
 		FastStack<CallStackItem> m_ExecutionStack = new FastStack<CallStackItem>(131072);
 		FastStack<CallStackItem> m_ExecutionStack = new FastStack<CallStackItem>(131072);
-		FastStack<ClosureContext> m_ClosureStack = new FastStack<ClosureContext>(131072);
 
 
 		IDebugger m_DebuggerAttached = null;
 		IDebugger m_DebuggerAttached = null;
 		DebuggerAction.ActionType m_DebuggerCurrentAction = DebuggerAction.ActionType.None;
 		DebuggerAction.ActionType m_DebuggerCurrentAction = DebuggerAction.ActionType.None;

+ 8 - 10
src/MoonSharp.Interpreter/Execution/VM/Processor/Processor_InstructionLoop.cs

@@ -11,7 +11,7 @@ namespace MoonSharp.Interpreter.Execution.VM
 	{
 	{
 		private RValue Processing_Loop()
 		private RValue Processing_Loop()
 		{
 		{
-			while (m_InstructionPtr < m_CurChunk.Code.Count && m_InstructionPtr >= 0)
+			while (true)
 			{
 			{
 				Instruction i = m_CurChunk.Code[m_InstructionPtr];
 				Instruction i = m_CurChunk.Code[m_InstructionPtr];
 
 
@@ -36,9 +36,6 @@ namespace MoonSharp.Interpreter.Execution.VM
 					case OpCode.Literal:
 					case OpCode.Literal:
 						m_ValueStack.Push(i.Value);
 						m_ValueStack.Push(i.Value);
 						break;
 						break;
-					case OpCode.Bool:
-						Bool(i);
-						break;
 					case OpCode.Add:
 					case OpCode.Add:
 						ExecAdd(i);
 						ExecAdd(i);
 						break;
 						break;
@@ -110,9 +107,6 @@ namespace MoonSharp.Interpreter.Execution.VM
 					case OpCode.Closure:
 					case OpCode.Closure:
 						m_ValueStack.Push(new RValue(new Closure(i.NumVal, i.SymbolList, m_ExecutionStack.Peek().LocalScope)));
 						m_ValueStack.Push(new RValue(new Closure(i.NumVal, i.SymbolList, m_ExecutionStack.Peek().LocalScope)));
 						break;
 						break;
-					case OpCode.ExitClsr:
-						this.LeaveClosure();
-						break;
 					case OpCode.BeginFn:
 					case OpCode.BeginFn:
 						ExecBeginFn(i);
 						ExecBeginFn(i);
 						break;
 						break;
@@ -121,6 +115,8 @@ namespace MoonSharp.Interpreter.Execution.VM
 						break;
 						break;
 					case OpCode.Ret:
 					case OpCode.Ret:
 						ExecRet(i);
 						ExecRet(i);
+						if (m_InstructionPtr < 0)
+							goto return_to_native_code;
 						break;
 						break;
 					case OpCode.Incr:
 					case OpCode.Incr:
 						ExecIncr(i);
 						ExecIncr(i);
@@ -162,12 +158,14 @@ namespace MoonSharp.Interpreter.Execution.VM
 						ExecExpTuple(i);
 						ExecExpTuple(i);
 						break;
 						break;
 					case OpCode.Invalid:
 					case OpCode.Invalid:
-						throw new NotImplementedException(string.Format("Compilation for {0} not implented yet!", i.Name));
+						throw new NotImplementedException(string.Format("Invalid opcode : {0}", i.Name));
 					default:
 					default:
 						throw new NotImplementedException(string.Format("Execution for {0} not implented yet!", i.OpCode));
 						throw new NotImplementedException(string.Format("Execution for {0} not implented yet!", i.OpCode));
 				}
 				}
 			}
 			}
 
 
+		return_to_native_code:
+
 			if (m_ValueStack.Count == 1)
 			if (m_ValueStack.Count == 1)
 				return m_ValueStack.Pop();
 				return m_ValueStack.Pop();
 			else if (m_ValueStack.Count == 0)
 			else if (m_ValueStack.Count == 0)
@@ -365,10 +363,10 @@ namespace MoonSharp.Interpreter.Execution.VM
 				{
 				{
 					BasePointer = m_ValueStack.Count,
 					BasePointer = m_ValueStack.Count,
 					ReturnAddress = m_InstructionPtr,
 					ReturnAddress = m_InstructionPtr,
-					Debug_EntryPoint = fn.Function.ByteCodeLocation
+					Debug_EntryPoint = fn.Function.ByteCodeLocation,
+					ClosureScope = fn.Function.ClosureContext
 				});
 				});
 				m_InstructionPtr = fn.Function.ByteCodeLocation;
 				m_InstructionPtr = fn.Function.ByteCodeLocation;
-				this.EnterClosure(fn.Function.ClosureContext);
 			}
 			}
 			else
 			else
 			{
 			{

+ 13 - 40
src/MoonSharp.Interpreter/Execution/VM/Processor/Processor_Scope.cs

@@ -8,17 +8,6 @@ namespace MoonSharp.Interpreter.Execution.VM
 {
 {
 	sealed partial class Processor
 	sealed partial class Processor
 	{
 	{
-
-		public void EnterClosure(ClosureContext closureValues)
-		{
-			m_ClosureStack.Push(closureValues);
-		}
-
-		public void LeaveClosure()
-		{
-			m_ClosureStack.RemoveLast();
-		}
-
 		private void NilifyBlockData(RuntimeScopeBlock runtimeScopeBlock)
 		private void NilifyBlockData(RuntimeScopeBlock runtimeScopeBlock)
 		{
 		{
 			int from = runtimeScopeBlock.From;
 			int from = runtimeScopeBlock.From;
@@ -56,16 +45,7 @@ namespace MoonSharp.Interpreter.Execution.VM
 				case LRefType.Local:
 				case LRefType.Local:
 					return m_ExecutionStack.Peek().LocalScope[symref.i_Index];
 					return m_ExecutionStack.Peek().LocalScope[symref.i_Index];
 				case LRefType.Upvalue:
 				case LRefType.Upvalue:
-					List<RValue> closureValues = m_ClosureStack.Count > 0 ? m_ClosureStack[m_ClosureStack.Count - 1] : null;
-
-					if (closureValues != null)
-					{
-						return closureValues[symref.i_Index];
-					}
-					else
-					{
-						throw new ScriptRuntimeException(null, "Invalid upvalue at resolution: {0}", symref.i_Name);
-					}
+					return m_ExecutionStack.Peek().ClosureScope[symref.i_Index];
 				case LRefType.Index:
 				case LRefType.Index:
 				case LRefType.Invalid:
 				case LRefType.Invalid:
 				default:
 				default:
@@ -93,16 +73,13 @@ namespace MoonSharp.Interpreter.Execution.VM
 					break;
 					break;
 				case LRefType.Upvalue:
 				case LRefType.Upvalue:
 					{
 					{
-						List<RValue> closureValues = m_ClosureStack.Count > 0 ? m_ClosureStack[m_ClosureStack.Count - 1] : null;
-
-						if (closureValues != null)
-						{
-							closureValues[symref.i_Index].Assign(value);
-						}
-						else
-						{
-							throw new ScriptRuntimeException(null, "Invalid upvalue at resolution: {0}", symref.i_Name);
-						}
+						var stackframe = m_ExecutionStack.Peek();
+
+						RValue v = stackframe.ClosureScope[symref.i_Index];
+						if (v == null)
+							stackframe.ClosureScope[symref.i_Index] = v = new RValue();
+
+						v.Assign(value);
 					}
 					}
 					break;
 					break;
 				case LRefType.Index:
 				case LRefType.Index:
@@ -127,16 +104,12 @@ namespace MoonSharp.Interpreter.Execution.VM
 				}
 				}
 			}
 			}
 
 
-			if (m_ClosureStack.Count > 0)
-			{
-				var closure = m_ClosureStack.Peek(0);
+			
+			var closure = stackframe.ClosureScope;
 
 
-				for (int i = 0; i < closure.Symbols.Length; i++)
-					if (closure.Symbols[i] == name)
-					{
-						return LRef.Upvalue(name, i);
-					}
-			}
+			for (int i = 0; i < closure.Symbols.Length; i++)
+				if (closure.Symbols[i] == name)
+					return LRef.Upvalue(name, i);
 
 
 			if (m_GlobalTable.HasStringSymbol(name))
 			if (m_GlobalTable.HasStringSymbol(name))
 				return LRef.Global(name);
 				return LRef.Global(name);

+ 3 - 4
src/MoonSharp.Interpreter/MoonSharp.Interpreter.csproj

@@ -74,9 +74,11 @@
   </ItemGroup>
   </ItemGroup>
   <ItemGroup>
   <ItemGroup>
     <Compile Include="CoreLib\BasicMethods.cs" />
     <Compile Include="CoreLib\BasicMethods.cs" />
+    <Compile Include="CoreLib\CoreLibModule.cs" />
     <Compile Include="CoreLib\MetaTableMethods.cs" />
     <Compile Include="CoreLib\MetaTableMethods.cs" />
     <Compile Include="DataStructs\Extension_Methods.cs" />
     <Compile Include="DataStructs\Extension_Methods.cs" />
     <Compile Include="DataStructs\FastStackDynamic.cs" />
     <Compile Include="DataStructs\FastStackDynamic.cs" />
+    <Compile Include="DataStructs\LinkedListIndex.cs" />
     <Compile Include="DataStructs\Slice.cs" />
     <Compile Include="DataStructs\Slice.cs" />
     <Compile Include="Debugging\DebuggerAction.cs" />
     <Compile Include="Debugging\DebuggerAction.cs" />
     <Compile Include="Debugging\IDebugger.cs" />
     <Compile Include="Debugging\IDebugger.cs" />
@@ -91,14 +93,11 @@
     <Compile Include="Errors\SyntaxErrorException.cs" />
     <Compile Include="Errors\SyntaxErrorException.cs" />
     <Compile Include="Execution\DataTypes\Closure.cs" />
     <Compile Include="Execution\DataTypes\Closure.cs" />
     <Compile Include="Execution\DataTypes\CallbackFunction.cs" />
     <Compile Include="Execution\DataTypes\CallbackFunction.cs" />
+    <Compile Include="Execution\DataTypes\TablePair.cs" />
     <Compile Include="Execution\Scopes\ClosureContext.cs" />
     <Compile Include="Execution\Scopes\ClosureContext.cs" />
     <Compile Include="Execution\Scopes\LoopTracker.cs" />
     <Compile Include="Execution\Scopes\LoopTracker.cs" />
-    <Compile Include="Execution\Scopes\OldScopeClasses\BuildTimeScope.cs" />
-    <Compile Include="Execution\Scopes\OldScopeClasses\BuildTimeScopeFrame.cs" />
     <Compile Include="Execution\Scopes\IClosureBuilder.cs" />
     <Compile Include="Execution\Scopes\IClosureBuilder.cs" />
     <Compile Include="Execution\DataTypes\LRefType.cs" />
     <Compile Include="Execution\DataTypes\LRefType.cs" />
-    <Compile Include="Execution\Scopes\OldScopeClasses\RuntimeScope.cs" />
-    <Compile Include="Execution\Scopes\OldScopeClasses\RuntimeScopeFrame.cs" />
     <Compile Include="Execution\DataTypes\LRef.cs" />
     <Compile Include="Execution\DataTypes\LRef.cs" />
     <Compile Include="Execution\Scopes\BuildTimeScope.cs" />
     <Compile Include="Execution\Scopes\BuildTimeScope.cs" />
     <Compile Include="Execution\Scopes\BuildTimeScopeBlock.cs" />
     <Compile Include="Execution\Scopes\BuildTimeScopeBlock.cs" />

+ 0 - 2
src/MoonSharp.Interpreter/Tree/Expressions/FunctionDefinitionExpression.cs

@@ -108,8 +108,6 @@ namespace MoonSharp.Interpreter.Tree.Expressions
 
 
 			m_Statement.Compile(bc);
 			m_Statement.Compile(bc);
 
 
-			bc.ExitClsr();
-
 			bc.Ret(0);
 			bc.Ret(0);
 
 
 			I.NumVal = bc.GetJumpPointForNextInstruction();
 			I.NumVal = bc.GetJumpPointForNextInstruction();

+ 4 - 4
src/PerformanceComparison/Program.cs

@@ -1,4 +1,4 @@
-#define PROFILER
+//#define PROFILER
 
 
 using System;
 using System;
 using System.Collections.Generic;
 using System.Collections.Generic;
@@ -16,12 +16,12 @@ namespace PerformanceComparison
 	class Program
 	class Program
 	{
 	{
 #if PROFILER
 #if PROFILER
-		const int ITERATIONS = 10;
+		const int ITERATIONS = 1000;
 #else
 #else
 		const int ITERATIONS = 1;
 		const int ITERATIONS = 1;
 #endif
 #endif
 
 
-		static  string scriptText = @"
+		static  string scriptText2 = @"
 			function move(n, src, dst, via)
 			function move(n, src, dst, via)
 				if n > 0 then
 				if n > 0 then
 					move(n - 1, src, via, dst)
 					move(n - 1, src, via, dst)
@@ -34,7 +34,7 @@ namespace PerformanceComparison
 				move(4, 1, 2, 3)
 				move(4, 1, 2, 3)
 			end
 			end
 			";
 			";
-		static  string scriptText2 = @"
+		static  string scriptText = @"
 N = 8
 N = 8
  
  
 board = {}
 board = {}