Răsfoiți Sursa

all statements executing - 2 lua suite failings

Xanathar 11 ani în urmă
părinte
comite
06035d38da

+ 3 - 3
src/MoonSharp.Interpreter.Tests/LuaTestSuiteExtract.cs

@@ -43,7 +43,7 @@ namespace MoonSharp.Interpreter.Tests
 				string.Join(", ", failedTests.Select(xi => xi.ToString()).ToArray())));
 				string.Join(", ", failedTests.Select(xi => xi.ToString()).ToArray())));
 		}
 		}
 
 
-		[Test][Ignore("VM Transition")]
+		[Test]
 		public void LuaSuite_Calls_LocalFunctionRecursion()
 		public void LuaSuite_Calls_LocalFunctionRecursion()
 		{
 		{
 			RunTest(@"
 			RunTest(@"
@@ -62,7 +62,7 @@ namespace MoonSharp.Interpreter.Tests
 				");
 				");
 		}
 		}
 
 
-		[Test][Ignore("VM Transition")]
+		[Test]
 		public void LuaSuite_Calls_Declarations()
 		public void LuaSuite_Calls_Declarations()
 		{
 		{
 			RunTest(@"
 			RunTest(@"
@@ -108,7 +108,7 @@ namespace MoonSharp.Interpreter.Tests
 				");
 				");
 		}
 		}
 
 
-		[Test][Ignore("VM Transition")]
+		[Test]
 		public void LuaSuite_Calls_Closures()
 		public void LuaSuite_Calls_Closures()
 		{
 		{
 			RunTest(@"
 			RunTest(@"

+ 50 - 7
src/MoonSharp.Interpreter.Tests/SimpleTests.cs

@@ -240,7 +240,50 @@ namespace MoonSharp.Interpreter.Tests
 		}
 		}
 
 
 
 
-		[Test][Ignore("VM Transition")]
+		[Test]
+		public void ForEachLoopWithBreak()
+		{
+			string script = @"    
+				x = 0
+				y = 0
+
+				t = { 2, 4, 6, 8, 10, 12 };
+
+				function iter (a, ii)
+				  ii = ii + 1
+				  local v = a[ii]
+				  if v then
+					return ii, v
+				  end
+				end
+    
+				function ipairslua (a)
+				  return iter, a, 0
+				end
+
+				for i,j in ipairslua(t) do
+					x = x + i
+					y = y + j
+
+					if (i >= 3) then
+						break
+					end
+				end
+    
+				return x, y";
+
+			RValue res = MoonSharpInterpreter.LoadFromString(script, null).Execute();
+
+			Assert.AreEqual(DataType.Tuple, res.Type);
+			Assert.AreEqual(2, res.Tuple.Length);
+			Assert.AreEqual(DataType.Number, res.Tuple[0].Type);
+			Assert.AreEqual(DataType.Number, res.Tuple[1].Type);
+			Assert.AreEqual(6, res.Tuple[0].Number);
+			Assert.AreEqual(12, res.Tuple[1].Number);
+		}
+
+
+		[Test]
 		public void ForEachLoop()
 		public void ForEachLoop()
 		{
 		{
 			string script = @"    
 			string script = @"    
@@ -249,11 +292,11 @@ namespace MoonSharp.Interpreter.Tests
 
 
 				t = { 2, 4, 6, 8, 10, 12 };
 				t = { 2, 4, 6, 8, 10, 12 };
 
 
-				function iter (a, i)
-				  i = i + 1
-				  local v = a[i]
+				function iter (a, ii)
+				  ii = ii + 1
+				  local v = a[ii]
 				  if v then
 				  if v then
-					return i, v
+					return ii, v
 				  end
 				  end
 				end
 				end
     
     
@@ -397,7 +440,7 @@ namespace MoonSharp.Interpreter.Tests
 			Assert.AreEqual(6, res.Number);
 			Assert.AreEqual(6, res.Number);
 		}
 		}
 
 
-		[Test][Ignore("VM Transition")]
+		[Test]
 		public void IterativeFactorialWithWhile()
 		public void IterativeFactorialWithWhile()
 		{
 		{
 			string script = @"    
 			string script = @"    
@@ -420,7 +463,7 @@ namespace MoonSharp.Interpreter.Tests
 
 
 
 
 
 
-		[Test][Ignore("VM Transition")]
+		[Test]
 		public void IterativeFactorialWithRepeatUntilAndScopeCheck()
 		public void IterativeFactorialWithRepeatUntilAndScopeCheck()
 		{
 		{
 			string script = @"    
 			string script = @"    

+ 30 - 11
src/MoonSharp.Interpreter/Execution/VM/Chunk.cs

@@ -54,7 +54,6 @@ namespace MoonSharp.Interpreter.Execution.VM
 			return Code.Count - 1;
 			return Code.Count - 1;
 		}
 		}
 
 
-
 		private Instruction Emit(Instruction c)
 		private Instruction Emit(Instruction c)
 		{
 		{
 			Code.Add(c);
 			Code.Add(c);
@@ -106,9 +105,9 @@ namespace MoonSharp.Interpreter.Execution.VM
 			return Emit(new Instruction() { OpCode = OpCode.Symbol, Symbol = symref });
 			return Emit(new Instruction() { OpCode = OpCode.Symbol, Symbol = symref });
 		}
 		}
 
 
-		public Instruction Jump(OpCode jumpOpCode, int idx)
+		public Instruction Jump(OpCode jumpOpCode, int idx, int optPar = 0)
 		{
 		{
-			return Emit(new Instruction() { OpCode = jumpOpCode, NumVal = idx });
+			return Emit(new Instruction() { OpCode = jumpOpCode, NumVal = idx, NumVal2 = optPar });
 		}
 		}
 
 
 		public Instruction MkTuple(int cnt)
 		public Instruction MkTuple(int cnt)
@@ -176,9 +175,9 @@ namespace MoonSharp.Interpreter.Execution.VM
 			return Emit(new Instruction() { OpCode = OpCode.ToNum });
 			return Emit(new Instruction() { OpCode = OpCode.ToNum });
 		}
 		}
 
 
-		public Instruction NSymStor(SymbolRef symb)
+		public Instruction SymStorN(SymbolRef symb)
 		{
 		{
-			return Emit(new Instruction() { OpCode = OpCode.NSymStor, Symbol = symb });
+			return Emit(new Instruction() { OpCode = OpCode.SymStorN, Symbol = symb });
 		}
 		}
 
 
 		public Instruction Incr(int i)
 		public Instruction Incr(int i)
@@ -186,18 +185,18 @@ namespace MoonSharp.Interpreter.Execution.VM
 			return Emit(new Instruction() { OpCode = OpCode.Incr, NumVal = i });
 			return Emit(new Instruction() { OpCode = OpCode.Incr, NumVal = i });
 		}
 		}
 
 
-		public Instruction IndexGet()
+		public Instruction Index()
 		{
 		{
-			return Emit(new Instruction() { OpCode = OpCode.IndexGet });
+			return Emit(new Instruction() { OpCode = OpCode.Index });
 		}
 		}
 
 
-		public Instruction IndexSet()
+		public Instruction IndexRef()
 		{
 		{
-			return Emit(new Instruction() { OpCode = OpCode.IndexSet });
+			return Emit(new Instruction() { OpCode = OpCode.IndexRef });
 		}
 		}
-		public Instruction IndexSetN()
+		public Instruction IndexRefN()
 		{
 		{
-			return Emit(new Instruction() { OpCode = OpCode.IndexSetN });
+			return Emit(new Instruction() { OpCode = OpCode.IndexRefN });
 		}
 		}
 
 
 		public Instruction NewTable()
 		public Instruction NewTable()
@@ -209,5 +208,25 @@ namespace MoonSharp.Interpreter.Execution.VM
 		{
 		{
 			return Emit(new Instruction() { OpCode = opCode, NumVal = regNum });
 			return Emit(new Instruction() { OpCode = opCode, NumVal = regNum });
 		}
 		}
+
+		public Instruction IterPrep()
+		{
+			return Emit(new Instruction() { OpCode = OpCode.IterPrep });
+		}
+
+		public Instruction ExpTuple(int stackOffset)
+		{
+			return Emit(new Instruction() { OpCode = OpCode.ExpTuple, NumVal = stackOffset });
+		}
+
+		public Instruction IterUpd()
+		{
+			return Emit(new Instruction() { OpCode = OpCode.IterUpd });
+		}
+
+		public Instruction Reverse(int p)
+		{
+			return Emit(new Instruction() { OpCode = OpCode.Reverse, NumVal = p });
+		}
 	}
 	}
 }
 }

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

@@ -22,22 +22,34 @@ namespace MoonSharp.Interpreter.Execution.VM
 
 
 			switch (OpCode)
 			switch (OpCode)
 			{
 			{
+				case OpCode.Closure:
+					append = string.Format("{0}{1:X8}({2})", GenSpaces(), NumVal, string.Join(",", SymbolList.Select(s => s.ToString()).ToArray()));
+					break;
+				case OpCode.Args:
+					append = string.Format("{0}({1})", GenSpaces(), string.Join(",", SymbolList.Select(s => s.ToString()).ToArray()));
+					break;
+				case OpCode.Enter:
+				case OpCode.Exit:
+					append = string.Format("{0}{1}", GenSpaces(), FrameToString(Frame));
+					break;
 				case OpCode.Debug:
 				case OpCode.Debug:
 					return string.Format("[[ {0} ]]", Name);
 					return string.Format("[[ {0} ]]", Name);
 				case OpCode.Load:
 				case OpCode.Load:
 				case OpCode.Symbol:
 				case OpCode.Symbol:
-				case OpCode.NSymStor:
+				case OpCode.SymStorN:
 					append = string.Format("{0}{1}", GenSpaces(), Symbol);
 					append = string.Format("{0}{1}", GenSpaces(), Symbol);
 					break;
 					break;
 				case OpCode.Literal:
 				case OpCode.Literal:
 					append = string.Format("{0}{1}", GenSpaces(), PurifyFromNewLines(Value));
 					append = string.Format("{0}{1}", GenSpaces(), PurifyFromNewLines(Value));
 					break;
 					break;
 				case OpCode.Nop:
 				case OpCode.Nop:
-					append = string.Format("{0}// {1}", GenSpaces(), Name);
+					append = string.Format("{0}#{1}", GenSpaces(), Name);
 					break;
 					break;
 				case OpCode.Call:
 				case OpCode.Call:
 				case OpCode.Ret:
 				case OpCode.Ret:
 				case OpCode.MkTuple:
 				case OpCode.MkTuple:
+				case OpCode.ExpTuple:
+				case OpCode.Reverse:
 				case OpCode.Incr:
 				case OpCode.Incr:
 				case OpCode.Pop:
 				case OpCode.Pop:
 				case OpCode.TmpClear:
 				case OpCode.TmpClear:
@@ -51,6 +63,7 @@ namespace MoonSharp.Interpreter.Execution.VM
 				case OpCode.Jf:
 				case OpCode.Jf:
 				case OpCode.Jump:
 				case OpCode.Jump:
 				case OpCode.JFor:
 				case OpCode.JFor:
+				case OpCode.JNil:
 					append = string.Format("{0}{1:X8}", GenSpaces(), NumVal);
 					append = string.Format("{0}{1:X8}", GenSpaces(), NumVal);
 					break;
 					break;
 				case OpCode.Invalid:
 				case OpCode.Invalid:
@@ -63,7 +76,15 @@ namespace MoonSharp.Interpreter.Execution.VM
 					break;
 					break;
 			}
 			}
 
 
-			return this.OpCode.ToString().ToLowerInvariant() + append;
+			return this.OpCode.ToString().ToUpperInvariant() + append;
+		}
+
+		private string FrameToString(RuntimeScopeFrame frame)
+		{
+			if (frame == null)
+				return "<null>";
+			else
+				return string.Format("{0}({1})", frame.RestartOfBase ? "function" : "block", frame.Count);
 		}
 		}
 
 
 		private string PurifyFromNewLines(RValue Value)
 		private string PurifyFromNewLines(RValue Value)
@@ -73,7 +94,7 @@ namespace MoonSharp.Interpreter.Execution.VM
 
 
 		private string GenSpaces()
 		private string GenSpaces()
 		{
 		{
-			return new string(' ', 9 - this.OpCode.ToString().Length);
+			return new string(' ', 10 - this.OpCode.ToString().Length);
 		}
 		}
 
 
 
 

+ 40 - 20
src/MoonSharp.Interpreter/Execution/VM/OpCode.cs

@@ -8,16 +8,40 @@ namespace MoonSharp.Interpreter.Execution.VM
 
 
 	public enum OpCode
 	public enum OpCode
 	{
 	{
+		// Meta-opcodes
 		Nop,		// Does not perform any operation.
 		Nop,		// Does not perform any operation.
 		Invalid,	// Crashes the executor with an unrecoverable NotImplementedException.
 		Invalid,	// Crashes the executor with an unrecoverable NotImplementedException.
+		Debug,		// Does not perform any operation.
+
+		// Stack ops and assignment
 		Pop,		// Discards the topmost n elements from the v-stack. 
 		Pop,		// Discards the topmost n elements from the v-stack. 
 		Load,		// Loads a value from the specified symbol, and pushes it on the v-stack.
 		Load,		// Loads a value from the specified symbol, and pushes it 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.
 		Literal,	// Pushes a literal (constant value) on the stack. 
 		Literal,	// Pushes a literal (constant value) on the stack. 
 		Symbol,		// Loads a symbol on the stack
 		Symbol,		// Loads a symbol on the stack
-		MkTuple,	// Creates a tuple from the topmost n values
+		SymStorN,	// Performs a store to a symbol, without needing the symbol on the v-stack and without extracting the operand from the v-stack.
+		Store,		// Performs a single value assignment [including table fields]
+		Assign,		// Performs complex assignment supporting tuples [including table fields]
+		Reverse,	// Reverses the last n elements of the stack
+		Closure,	// Creates a closure on the top of the v-stack, using the symbols for upvalues and num-val for entry point of the function.
+
+		// Stack-frame ops and calls
+		Enter,		// Enters a new 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
+		ExitClsr,	// Exits a closure at runtime
+		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.
+		Ret,		// Pops the top n values of the v-stack. Then pops an X value from the v-stack. Then pops X values from the v-stack. Afterwards, it pushes the top n values popped in the first step, pops the top of the x-stack and jumps to that location.
+
+		// Jumps
+		Jump,		// Jumps to the specified PC
+		Jf,			// Pops the top of the v-stack and jumps to the specified location if it's false
+		JNil,		// Jumps if the top of the stack is nil
+		JFor,		// Peeks at the top, top-1 and top-2 values of the v-stack which it assumes to be numbers. Then if top-1 is less than zero, checks if top is <= top-2, otherwise it checks that top is >= top-2. Then if the condition is false, it jumps.
 		JtOrPop,	// Peeks at the topmost value of the v-stack as a boolean. If true, it performs a jump, otherwise it removes the topmost value from the v-stack.
 		JtOrPop,	// Peeks at the topmost value of the v-stack as a boolean. If true, it performs a jump, otherwise it removes the topmost value from the v-stack.
 		JfOrPop,	// Peeks at the topmost value of the v-stack as a boolean. If false, it performs a jump, otherwise it removes the topmost value from the v-stack.
 		JfOrPop,	// Peeks at the topmost value of the v-stack as a boolean. If false, it performs a jump, otherwise it removes the topmost value from the v-stack.
+
+		// Operators
 		Concat,		// Concatenation of the two topmost operands on the v-stack
 		Concat,		// Concatenation of the two topmost operands on the v-stack
 		LessEq,		// Compare <= of the two topmost operands on the v-stack
 		LessEq,		// Compare <= of the two topmost operands on the v-stack
 		Less,		// Compare < of the two topmost operands on the v-stack
 		Less,		// Compare < of the two topmost operands on the v-stack
@@ -31,33 +55,29 @@ namespace MoonSharp.Interpreter.Execution.VM
 		Len,		// Size operator of the topmost operand on the v-stack
 		Len,		// Size operator of the topmost operand on the v-stack
 		Neg,		// Negation (unary minus) operator of the topmost operand on the v-stack
 		Neg,		// Negation (unary minus) operator of the topmost operand on the v-stack
 		Power,		// Power of the two topmost operands on the v-stack
 		Power,		// Power of the two topmost operands on the v-stack
-		Bool,		// Converts the top of the v-stack to a boolean
-		Debug,		// Does not perform any operation.
-		Enter,		// Enters a new 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
-		Closure,	// Creates a closure on the top of the v-stack, using the symbols for upvalues and num-val for entry point of the function.
-		ExitClsr,	// Exits a closure at runtime
-		Args,		// Takes the arguments passed to a function and sets the appropriate symbols in the local scope
-		Jump,		// Jumps to the specified PC
-		Ret,		// Pops the top n values of the v-stack. Then pops an X value from the v-stack. Then pops X values from the v-stack. Afterwards, it pushes the top n values popped in the first step, pops the top of the x-stack and jumps to that location.
-		Jf,			// Pops the top of the v-stack and jumps to the specified location if it's false
 
 
+		// Type conversions and manipulations
+		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.
-		JFor,		// Peeks at the top, top-1 and top-2 values of the v-stack which it assumes to be numbers. Then if top-1 is less than zero, checks if top is <= top-2, otherwise it checks that top is >= top-2. Then if the condition is false, it jumps.
 		ToNum,		// Converts the top of the stack to a number
 		ToNum,		// Converts the top of the stack to a number
-		NSymStor,	// Performs a store to a symbol, without needing the symbol on the v-stack and without extracting the operand from the v-stack.
-		Store,		// Performs a single value assignment [including table fields]
-		Assign,		// Performs complex assignment supporting tuples [including table fields]
-		IndexGet,	// Performs an index operation, pushing the indexed value on the stack.
-		IndexSet,	// Performs an index operation, pushing a writable indexded value on the stack.
-		IndexSetN,	// Performs an index operation, pushing a writable indexed value on the stack, does not pop the table.
+		ExpTuple,	// Expands a tuple on the stack
+
+		// Tables
+		Index,		// Performs an index operation, pushing the indexed value on the stack.
+		IndexRef,	// Performs an index operation, pushing a writable indexded value on the stack.
+		IndexRefN,	// Performs an index operation, pushing a writable indexed value on the stack, does not pop the table.
 		NewTable,	// Creates a new table on the stack
 		NewTable,	// Creates a new table on the stack
 
 
+		// ScratchPad
 		TmpPeek,	// Peeks the top of the stack in a temporary reg. 
 		TmpPeek,	// Peeks the top of the stack in a temporary reg. 
 		TmpPush,	// Pushes a temporary reg on the top of the stack. 
 		TmpPush,	// Pushes a temporary reg on the top of the stack. 
 		TmpPop,		// Pops the top of the stack in a temporary reg. 
 		TmpPop,		// Pops the top of the stack in a temporary reg. 
 		TmpClear,	// Clears a temporary reg
 		TmpClear,	// Clears a temporary reg
 
 
+		// Iterators
+		IterPrep,   // Prepares an interator for execution 
+		IterUpd,	// Updates the var part of an iterator
+
 	}
 	}
 }
 }

+ 126 - 21
src/MoonSharp.Interpreter/Execution/VM/VmExecutor.cs

@@ -95,17 +95,17 @@ namespace MoonSharp.Interpreter.Execution.VM
 				Instruction i = m_CurChunk.Code[m_InstructionPtr];
 				Instruction i = m_CurChunk.Code[m_InstructionPtr];
 
 
 
 
-				//if (m_DoDebug)
-				//{
-				//	DebugInterface(i);
-				//}
-
-				//if (System.Diagnostics.Debugger.IsAttached && m_StepEnabled)
-				//{
-				//	ConsoleKeyInfo cki = Console.ReadKey();
-				//	if (cki.Key == ConsoleKey.Escape)
-				//		m_StepEnabled = false;
-				//}
+				if (m_DoDebug)
+				{
+					DebugInterface(i);
+				}
+
+				if (System.Diagnostics.Debugger.IsAttached && m_StepEnabled)
+				{
+					ConsoleKeyInfo cki = Console.ReadKey();
+					if (cki.Key == ConsoleKey.Escape)
+						m_StepEnabled = false;
+				}
 
 
 				++m_InstructionPtr;
 				++m_InstructionPtr;
 
 
@@ -150,6 +150,9 @@ namespace MoonSharp.Interpreter.Execution.VM
 					case OpCode.LessEq:
 					case OpCode.LessEq:
 						ExecLessEq(i);
 						ExecLessEq(i);
 						break;
 						break;
+					case OpCode.Less:
+						ExecLess(i);
+						break;
 					case OpCode.Call:
 					case OpCode.Call:
 						ExecCall(i);
 						ExecCall(i);
 						break;
 						break;
@@ -163,6 +166,9 @@ namespace MoonSharp.Interpreter.Execution.VM
 					case OpCode.JtOrPop:
 					case OpCode.JtOrPop:
 						ExecShortCircuitingOperator(i);
 						ExecShortCircuitingOperator(i);
 						break;
 						break;
+					case OpCode.JNil:
+						ExecJNil(i);
+						break;
 					case OpCode.Store:
 					case OpCode.Store:
 						ExecStore(i);
 						ExecStore(i);
 						break;
 						break;
@@ -205,20 +211,20 @@ namespace MoonSharp.Interpreter.Execution.VM
 					case OpCode.ToNum:
 					case OpCode.ToNum:
 						m_ValueStack.Push(m_ValueStack.Pop().AsNumber());
 						m_ValueStack.Push(m_ValueStack.Pop().AsNumber());
 						break;
 						break;
-					case OpCode.NSymStor:
-						ExecNSymStor(i);
+					case OpCode.SymStorN:
+						ExecSymStorN(i);
 						break;
 						break;
 					case OpCode.JFor:
 					case OpCode.JFor:
 						ExecJFor(i);
 						ExecJFor(i);
 						break;
 						break;
-					case OpCode.IndexGet:
+					case OpCode.Index:
 						ExecIndexGet(i);
 						ExecIndexGet(i);
 						break;
 						break;
-					case OpCode.IndexSet:
-						ExecIndexSet(i, false);
+					case OpCode.IndexRef:
+						ExecIndexRef(i, false);
 						break;
 						break;
-					case OpCode.IndexSetN:
-						ExecIndexSet(i, true);
+					case OpCode.IndexRefN:
+						ExecIndexRef(i, true);
 						break;
 						break;
 					case OpCode.NewTable:
 					case OpCode.NewTable:
 						m_ValueStack.Push(new RValue(new Table()));
 						m_ValueStack.Push(new RValue(new Table()));
@@ -232,12 +238,24 @@ namespace MoonSharp.Interpreter.Execution.VM
 					case OpCode.TmpPop:
 					case OpCode.TmpPop:
 						m_TempRegs[i.NumVal] = m_ValueStack.Pop();
 						m_TempRegs[i.NumVal] = m_ValueStack.Pop();
 						break;
 						break;
+					case OpCode.Reverse:
+						ExecReverse(i);
+						break;
 					case OpCode.Len:
 					case OpCode.Len:
 						ExecLen(i);
 						ExecLen(i);
 						break;
 						break;
 					case OpCode.TmpPush:
 					case OpCode.TmpPush:
 						m_ValueStack.Push(m_TempRegs[i.NumVal]);
 						m_ValueStack.Push(m_TempRegs[i.NumVal]);
 						break;
 						break;
+					case OpCode.IterPrep:
+						ExecIterPrep(i);
+						break;
+					case OpCode.IterUpd:
+						ExecIterUpd(i);
+						break;
+					case OpCode.ExpTuple:
+						ExecExpTuple(i);
+						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("Compilation for {0} not implented yet!", i.Name));
 					default:
 					default:
@@ -254,6 +272,75 @@ namespace MoonSharp.Interpreter.Execution.VM
 
 
 		}
 		}
 
 
+		private void ExecJNil(Instruction i)
+		{
+			RValue v = m_ValueStack.Pop();
+
+			if (v.Type == DataType.Nil)
+				m_InstructionPtr = i.NumVal;
+		}
+
+		private void ExecIterUpd(Instruction i)
+		{
+			RValue v = m_ValueStack.Peek(0);
+			RValue t = m_ValueStack.Peek(1);
+			t.Tuple[2] = v;
+		}
+
+		private void ExecExpTuple(Instruction i)
+		{
+			RValue t = m_ValueStack.Peek(i.NumVal);
+
+			if (t.Type == DataType.Tuple)
+			{
+				for (int idx = 0; idx < t.Tuple.Length; idx++)
+					m_ValueStack.Push(t.Tuple[idx]);
+			}
+			else
+			{
+				m_ValueStack.Push(t);
+			}
+			
+		}
+
+		private void ExecIterPrep(Instruction i)
+		{
+			RValue v = m_ValueStack.Pop();
+
+			if (v.Type != DataType.Tuple)
+			{
+				v = new RValue(new RValue[] { v, RValue.Nil, RValue.Nil });
+			}
+			else if (v.Tuple.Length > 3)
+			{
+				v = new RValue(new RValue[] { 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 });
+			}
+			else if (v.Tuple.Length == 1)
+			{
+				v = new RValue(new RValue[] { v.Tuple[0], RValue.Nil, RValue.Nil });
+			}
+
+			m_ValueStack.Push(v);
+		}
+
+		private void ExecReverse(Instruction i)
+		{
+			int cnt = i.NumVal;
+			int cnth = cnt / 2;
+
+			int len = m_ValueStack.Count - 1;
+
+			for (int idx = 0; idx < cnth; idx++)
+			{
+				var tmp = m_ValueStack[len - idx];
+				m_ValueStack[len - idx] = m_ValueStack[len - (cnt - 1 - idx)];
+				m_ValueStack[len - (cnt - 1 - idx)] = tmp;
+			}
+		}
 
 
 
 
 		private void ExecExit(Instruction i)
 		private void ExecExit(Instruction i)
@@ -356,6 +443,8 @@ namespace MoonSharp.Interpreter.Execution.VM
 			for (int i = 0; i < I.SymbolList.Length; i++)
 			for (int i = 0; i < I.SymbolList.Length; i++)
 			{
 			{
 				m_Scope.Assign(I.SymbolList[i], m_ValueStack.Peek(i + 1));
 				m_Scope.Assign(I.SymbolList[i], m_ValueStack.Peek(i + 1));
+
+				Console.WriteLine("ARGS: {0} <- {1}", I.SymbolList[i], m_ValueStack.Peek(i + 1));
 			}
 			}
 		}
 		}
 
 
@@ -423,6 +512,8 @@ namespace MoonSharp.Interpreter.Execution.VM
 
 
 			if (r.Type == DataType.Table)
 			if (r.Type == DataType.Table)
 				m_ValueStack.Push(new RValue(r.Table.Length));
 				m_ValueStack.Push(new RValue(r.Table.Length));
+			else if (r.Type == DataType.String)
+				m_ValueStack.Push(new RValue(r.String.Length));
 			else
 			else
 				throw new NotImplementedException("Meta operators");
 				throw new NotImplementedException("Meta operators");
 		}
 		}
@@ -488,6 +579,20 @@ namespace MoonSharp.Interpreter.Execution.VM
 			m_ValueStack.Push(new RValue(r.Equals(l)));
 			m_ValueStack.Push(new RValue(r.Equals(l)));
 		}
 		}
 
 
+		private void ExecLess(Instruction i)
+		{
+			RValue r = m_ValueStack.Pop();
+			RValue l = m_ValueStack.Pop();
+
+			if (r.Type == DataType.Number && r.Type == DataType.Number)
+			{
+				m_ValueStack.Push(new RValue(l.Number < r.Number));
+			}
+			else
+			{
+				throw new NotImplementedException("Comparison between non numbers!");
+			}
+		}
 
 
 		private void ExecLessEq(Instruction i)
 		private void ExecLessEq(Instruction i)
 		{
 		{
@@ -556,7 +661,7 @@ namespace MoonSharp.Interpreter.Execution.VM
 			}
 			}
 		}
 		}
 
 
-		private void ExecIndexSet(Instruction i, bool keepOnStack)
+		private void ExecIndexRef(Instruction i, bool keepOnStack)
 		{
 		{
 			RValue indexValue = m_ValueStack.Pop();
 			RValue indexValue = m_ValueStack.Pop();
 			RValue baseValue = keepOnStack ? m_ValueStack.Peek() : m_ValueStack.Pop();
 			RValue baseValue = keepOnStack ? m_ValueStack.Peek() : m_ValueStack.Pop();
@@ -581,7 +686,7 @@ namespace MoonSharp.Interpreter.Execution.VM
 		}
 		}
 
 
 
 
-		private void ExecNSymStor(Instruction i)
+		private void ExecSymStorN(Instruction i)
 		{
 		{
 			m_Scope.Assign(i.Symbol, m_ValueStack.Peek());
 			m_Scope.Assign(i.Symbol, m_ValueStack.Peek());
 		}
 		}
@@ -597,7 +702,7 @@ namespace MoonSharp.Interpreter.Execution.VM
 			m_ValueStack.CropAtCount(m_ValueStack.Count - i.NumVal - i.NumVal2);
 			m_ValueStack.CropAtCount(m_ValueStack.Count - i.NumVal - i.NumVal2);
 		}
 		}
 
 
-		public void Internal_MultiAssign(Slice<RValue> lValues, Slice<RValue> rValues)
+		private void Internal_MultiAssign(Slice<RValue> lValues, Slice<RValue> rValues)
 		{
 		{
 			int li = 0;
 			int li = 0;
 			int rValues_Count = rValues.Count;
 			int rValues_Count = rValues.Count;

+ 1 - 0
src/MoonSharp.Interpreter/MoonSharp.Interpreter.csproj

@@ -108,6 +108,7 @@
     <Compile Include="Tree\Expression.cs" />
     <Compile Include="Tree\Expression.cs" />
     <Compile Include="Tree\Expressions\OperatorExpression.cs" />
     <Compile Include="Tree\Expressions\OperatorExpression.cs" />
     <Compile Include="Tree\Expressions\SymbolRefExpression.cs" />
     <Compile Include="Tree\Expressions\SymbolRefExpression.cs" />
+    <Compile Include="Tree\Loop.cs" />
     <Compile Include="Tree\NodeBase.cs" />
     <Compile Include="Tree\NodeBase.cs" />
     <Compile Include="Tree\NodeFactory.cs" />
     <Compile Include="Tree\NodeFactory.cs" />
     <Compile Include="Tree\Statements\AssignmentStatement.cs" />
     <Compile Include="Tree\Statements\AssignmentStatement.cs" />

+ 2 - 2
src/MoonSharp.Interpreter/Properties/AssemblyInfo.cs

@@ -8,7 +8,7 @@ using System.Runtime.InteropServices;
 [assembly: AssemblyTitle("MoonSharp.Interpreter")]
 [assembly: AssemblyTitle("MoonSharp.Interpreter")]
 [assembly: AssemblyDescription("Interpreter for the MoonSharp language")]
 [assembly: AssemblyDescription("Interpreter for the MoonSharp language")]
 [assembly: AssemblyConfiguration("")]
 [assembly: AssemblyConfiguration("")]
-[assembly: AssemblyCompany("Marco Mastropaolo")]
+[assembly: AssemblyCompany("http://www.moonsharp.org")]
 [assembly: AssemblyProduct("MoonSharp.Interpreter")]
 [assembly: AssemblyProduct("MoonSharp.Interpreter")]
 [assembly: AssemblyCopyright("Copyright ©  2014, Marco Mastropaolo")]
 [assembly: AssemblyCopyright("Copyright ©  2014, Marco Mastropaolo")]
 [assembly: AssemblyTrademark("")]
 [assembly: AssemblyTrademark("")]
@@ -32,5 +32,5 @@ using System.Runtime.InteropServices;
 // You can specify all the values or you can default the Build and Revision Numbers 
 // You can specify all the values or you can default the Build and Revision Numbers 
 // by using the '*' as shown below:
 // by using the '*' as shown below:
 // [assembly: AssemblyVersion("1.0.*")]
 // [assembly: AssemblyVersion("1.0.*")]
-[assembly: AssemblyVersion("0.1.1")]
+[assembly: AssemblyVersion("0.1.8.*")]
 [assembly: AssemblyFileVersion("1.0.0.0")]
 [assembly: AssemblyFileVersion("1.0.0.0")]

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

@@ -48,7 +48,7 @@ namespace MoonSharp.Interpreter.Tree.Expressions
 		{
 		{
 			m_BaseExp.Compile(bc);
 			m_BaseExp.Compile(bc);
 			m_IndexExp.Compile(bc);
 			m_IndexExp.Compile(bc);
-			bc.IndexGet();
+			bc.Index();
 		}
 		}
 
 
 
 
@@ -57,7 +57,7 @@ namespace MoonSharp.Interpreter.Tree.Expressions
 		{
 		{
 			m_BaseExp.Compile(bc);
 			m_BaseExp.Compile(bc);
 			m_IndexExp.Compile(bc);
 			m_IndexExp.Compile(bc);
-			bc.IndexSet();
+			bc.IndexRef();
 		}
 		}
 	}
 	}
 }
 }

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

@@ -66,7 +66,7 @@ namespace MoonSharp.Interpreter.Tree.Expressions
 			foreach (var kvp in m_CtorArgs)
 			foreach (var kvp in m_CtorArgs)
 			{
 			{
 				kvp.Key.Compile(bc);
 				kvp.Key.Compile(bc);
-				bc.IndexSetN();
+				bc.IndexRefN();
 				kvp.Value.Compile(bc);
 				kvp.Value.Compile(bc);
 				bc.Store();
 				bc.Store();
 			}
 			}
@@ -74,7 +74,7 @@ namespace MoonSharp.Interpreter.Tree.Expressions
 			for (int i = 0; i < m_PositionalValues.Count; i++)
 			for (int i = 0; i < m_PositionalValues.Count; i++)
 			{
 			{
 				bc.Literal(new RValue(i+1));
 				bc.Literal(new RValue(i+1));
-				bc.IndexSetN();
+				bc.IndexRefN();
 				m_PositionalValues[i].Compile(bc);
 				m_PositionalValues[i].Compile(bc);
 				bc.Store();
 				bc.Store();
 			}
 			}

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

@@ -67,13 +67,15 @@ namespace MoonSharp.Interpreter.Tree
 			{
 			{
 				bc.TempOp(OpCode.TmpPeek, 0);
 				bc.TempOp(OpCode.TmpPeek, 0);
 				bc.Literal(new RValue(m_Name));
 				bc.Literal(new RValue(m_Name));
-				bc.IndexGet();
+				bc.Index();
 			}
 			}
 
 
 
 
-			for (int i = m_Arguments.Length - 1; i >= 0; i--)
+			for (int i = 0; i < m_Arguments.Length; i++)
 				m_Arguments[i].Compile(bc);
 				m_Arguments[i].Compile(bc);
 
 
+			bc.Reverse(m_Arguments.Length);
+
 			if (string.IsNullOrEmpty(m_Name))
 			if (string.IsNullOrEmpty(m_Name))
 			{
 			{
 				bc.Call(m_Arguments.Length);
 				bc.Call(m_Arguments.Length);

+ 22 - 0
src/MoonSharp.Interpreter/Tree/Loop.cs

@@ -0,0 +1,22 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using MoonSharp.Interpreter.Execution;
+using MoonSharp.Interpreter.Execution.VM;
+
+namespace MoonSharp.Interpreter.Tree
+{
+	internal class Loop : ILoop
+	{
+		public RuntimeScopeFrame Scope;
+		public List<Instruction> BreakJumps = new List<Instruction>();
+
+		public void CompileBreak(Chunk bc)
+		{
+			bc.Exit(Scope);
+			BreakJumps.Add(bc.Jump(OpCode.Jump, -1));
+		}
+	}
+
+}

+ 109 - 49
src/MoonSharp.Interpreter/Tree/Statements/ForEachLoopStatement.cs

@@ -3,6 +3,7 @@ using System.Collections.Generic;
 using System.Linq;
 using System.Linq;
 using System.Text;
 using System.Text;
 using MoonSharp.Interpreter.Execution;
 using MoonSharp.Interpreter.Execution;
+using MoonSharp.Interpreter.Execution.VM;
 using MoonSharp.Interpreter.Grammar;
 using MoonSharp.Interpreter.Grammar;
 
 
 namespace MoonSharp.Interpreter.Tree.Statements
 namespace MoonSharp.Interpreter.Tree.Statements
@@ -11,7 +12,7 @@ namespace MoonSharp.Interpreter.Tree.Statements
 	{
 	{
 		RuntimeScopeFrame m_StackFrame;
 		RuntimeScopeFrame m_StackFrame;
 		SymbolRef[] m_Names;
 		SymbolRef[] m_Names;
-		Expression[] m_RValues;
+		Expression m_RValues;
 		Statement m_Block;
 		Statement m_Block;
 
 
 
 
@@ -22,10 +23,7 @@ namespace MoonSharp.Interpreter.Tree.Statements
 
 
 			var explist = context.explist();
 			var explist = context.explist();
 
 
-			m_RValues = explist
-			.exp()
-			.Select(e => NodeFactory.CreateExpression(e, lcontext))
-			.ToArray();
+			m_RValues = NodeFactory.CreateExpression(explist, lcontext);
 
 
 			lcontext.Scope.PushBlock();
 			lcontext.Scope.PushBlock();
 
 
@@ -39,74 +37,136 @@ namespace MoonSharp.Interpreter.Tree.Statements
 			m_StackFrame = lcontext.Scope.Pop();
 			m_StackFrame = lcontext.Scope.Pop();
 		}
 		}
 
 
+		public override void Compile(Chunk bc)
+		{
+			//for var_1, ···, var_n in explist do block end
+
+			Loop L = new Loop()
+			{
+				Scope = m_StackFrame
+			};
+			bc.LoopTracker.Loops.Push(L);
+
+			// get iterator tuple
+			m_RValues.Compile(bc);
+
+			// prepares iterator tuple - stack : iterator-tuple
+			bc.IterPrep();
+
+			// loop start - stack : iterator-tuple
+			int start = bc.GetJumpPointForNextInstruction();
+			bc.Enter(m_StackFrame);
+
+			// push all iterating variables - stack : iterator-tuple, iter-var-symbols
+			foreach (SymbolRef s in m_Names)
+				bc.Symbol(s);
+
+			// expand the tuple - stack : iterator-tuple, iter-var-symbols, f, var, s
+			bc.ExpTuple(m_Names.Length);  
+			bc.Reverse(2);
+
+			// calls f(s, var) - stack : iterator-tuple, iter-var-symbols, iteration result
+			bc.Call(2);
+
+			// assigns to iter-var-symbols - stack : iterator-tuple
+			bc.Assign(m_Names.Length, 1);
+
+			// repushes the main iterator var - stack : iterator-tuple, main-iterator-var
+			bc.Load(m_Names[0]);
 
 
+			// updates the iterator tuple - stack : iterator-tuple, main-iterator-var
+			bc.IterUpd();
+
+			// checks head, jumps if nil - stack : iterator-tuple, main-iterator-var
+			var endjump = bc.Jump(OpCode.JNil, -1);
+
+			// executes the stuff - stack : iterator-tuple
+			m_Block.Compile(bc);
+
+			// loop back again - stack : iterator-tuple
+			bc.Leave(m_StackFrame);
+			bc.Jump(OpCode.Jump, start);
+
+			int exitpointLoopExit = bc.GetJumpPointForNextInstruction();
+			bc.Leave(m_StackFrame);
+
+			int exitpointBreaks = bc.GetJumpPointForNextInstruction();
+
+			bc.Pop();
+
+			foreach (Instruction i in L.BreakJumps)
+				i.NumVal = exitpointBreaks;
+
+			endjump.NumVal = exitpointLoopExit;
+		}
 
 
 
 
 		public override ExecutionFlow Exec(RuntimeScope scope)
 		public override ExecutionFlow Exec(RuntimeScope scope)
 		{
 		{
-			List<RValue> values = m_RValues
-				.Select(r => r.Eval(scope))
-				.SelectMany(r => r.UnpackedTuple())
-				.ToList();
+			return ExecutionFlow.None;
+			//List<RValue> values = m_RValues
+			//	.Select(r => r.Eval(scope))
+			//	.SelectMany(r => r.UnpackedTuple())
+			//	.ToList();
 
 
-			while (values.Count < 3)
-				values.Add(RValue.Nil);
+			//while (values.Count < 3)
+			//	values.Add(RValue.Nil);
 
 
-			RValue F = values[0];
-			RValue[] args = new RValue[2];
+			//RValue F = values[0];
+			//RValue[] args = new RValue[2];
 
 
-			args[0] = values[1];
-			args[1] = values[2];
+			//args[0] = values[1];
+			//args[1] = values[2];
 
 
 
 
-			while (true)
-			{
-				if (F.Type != DataType.ClrFunction)
-					throw RuntimeError("Attempt to call non-function");
+			//while (true)
+			//{
+			//	if (F.Type != DataType.ClrFunction)
+			//		throw RuntimeError("Attempt to call non-function");
 
 
-				RValue tuple = F.Callback.Invoke(scope, args);
+			//	RValue tuple = F.Callback.Invoke(scope, args);
 
 
-				scope.PushFrame(m_StackFrame);
+			//	scope.PushFrame(m_StackFrame);
 
 
-				int iv = 0;
-				RValue firstVal = null;
+			//	int iv = 0;
+			//	RValue firstVal = null;
 
 
-				foreach (var vv in tuple.UnpackedTuple())
-				{
-					if (iv >= m_Names.Length)
-						break;
+			//	foreach (var vv in tuple.UnpackedTuple())
+			//	{
+			//		if (iv >= m_Names.Length)
+			//			break;
 
 
-					scope.Assign(m_Names[iv], vv);
+			//		scope.Assign(m_Names[iv], vv);
 
 
-					if (firstVal == null)
-						args[1] = firstVal = vv;
+			//		if (firstVal == null)
+			//			args[1] = firstVal = vv;
 
 
-					++iv;
-				}
+			//		++iv;
+			//	}
 
 
 
 
-				while (iv < m_Names.Length)
-				{
-					scope.Assign(m_Names[iv], RValue.Nil);
-					++iv;
-				}
+			//	while (iv < m_Names.Length)
+			//	{
+			//		scope.Assign(m_Names[iv], RValue.Nil);
+			//		++iv;
+			//	}
 
 
-				if (firstVal == null || firstVal.Type == DataType.Nil)
-				{
-					scope.PopFrame(m_StackFrame);
-					return ExecutionFlow.None;
-				}
+			//	if (firstVal == null || firstVal.Type == DataType.Nil)
+			//	{
+			//		scope.PopFrame(m_StackFrame);
+			//		return ExecutionFlow.None;
+			//	}
 
 
-				ExecutionFlow flow = m_Block.Exec(scope);
+			//	ExecutionFlow flow = m_Block.Exec(scope);
 
 
-				scope.PopFrame(m_StackFrame);
+			//	scope.PopFrame(m_StackFrame);
 
 
-				if (flow.Type == ExecutionFlowType.Return)
-					return flow;
+			//	if (flow.Type == ExecutionFlowType.Return)
+			//		return flow;
 
 
-				if (flow.Type == ExecutionFlowType.Break)
-					return ExecutionFlow.None;
-			}
+			//	if (flow.Type == ExecutionFlowType.Break)
+			//		return ExecutionFlow.None;
+			//}
 		}
 		}
 	}
 	}
 }
 }

+ 1 - 12
src/MoonSharp.Interpreter/Tree/Statements/ForLoopStatement.cs

@@ -65,17 +65,6 @@ namespace MoonSharp.Interpreter.Tree.Statements
 			return ExecutionFlow.None;
 			return ExecutionFlow.None;
 		}
 		}
 
 
-		private class Loop : ILoop
-		{
-			public RuntimeScopeFrame Scope;
-			public List<Instruction> BreakJumps = new List<Instruction>();
-
-			public void CompileBreak(Chunk bc)
-			{
-				bc.Exit(Scope);
-				BreakJumps.Add(bc.Jump(OpCode.Jump, -1));
-			}
-		}
 
 
 
 
 		public override void Compile(Chunk bc)
 		public override void Compile(Chunk bc)
@@ -97,7 +86,7 @@ namespace MoonSharp.Interpreter.Tree.Statements
 			int start = bc.GetJumpPointForNextInstruction();
 			int start = bc.GetJumpPointForNextInstruction();
 			var jumpend = bc.Jump(OpCode.JFor, -1);
 			var jumpend = bc.Jump(OpCode.JFor, -1);
 			bc.Enter(m_StackFrame);
 			bc.Enter(m_StackFrame);
-			bc.NSymStor(m_VarName);
+			bc.SymStorN(m_VarName);
 			m_InnerBlock.Compile(bc);
 			m_InnerBlock.Compile(bc);
 			bc.Debug("..end");
 			bc.Debug("..end");
 			bc.Leave(m_StackFrame);
 			bc.Leave(m_StackFrame);

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

@@ -110,12 +110,12 @@ namespace MoonSharp.Interpreter.Tree.Statements
 				foreach (string str in m_TableAccessors)
 				foreach (string str in m_TableAccessors)
 				{
 				{
 					bc.Literal(new RValue(str));
 					bc.Literal(new RValue(str));
-					bc.IndexGet();
+					bc.Index();
 				}
 				}
 
 
 				bc.Literal(new RValue(m_MethodName));
 				bc.Literal(new RValue(m_MethodName));
 
 
-				bc.IndexSet();
+				bc.IndexRef();
 
 
 				m_FuncDef.Compile(bc);
 				m_FuncDef.Compile(bc);
 
 

+ 27 - 0
src/MoonSharp.Interpreter/Tree/Statements/RepeatStatement.cs

@@ -3,6 +3,7 @@ using System.Collections.Generic;
 using System.Linq;
 using System.Linq;
 using System.Text;
 using System.Text;
 using MoonSharp.Interpreter.Execution;
 using MoonSharp.Interpreter.Execution;
+using MoonSharp.Interpreter.Execution.VM;
 using MoonSharp.Interpreter.Grammar;
 using MoonSharp.Interpreter.Grammar;
 
 
 namespace MoonSharp.Interpreter.Tree.Statements
 namespace MoonSharp.Interpreter.Tree.Statements
@@ -51,5 +52,31 @@ namespace MoonSharp.Interpreter.Tree.Statements
 			return ExecutionFlow.None;
 			return ExecutionFlow.None;
 		}
 		}
 
 
+		public override void Compile(Chunk bc)
+		{
+			Loop L = new Loop()
+			{
+				Scope = m_StackFrame
+			};
+
+			bc.LoopTracker.Loops.Push(L);
+
+			int start = bc.GetJumpPointForNextInstruction();
+
+			bc.Enter(m_StackFrame);
+			m_Block.Compile(bc);
+			bc.Debug("..end");
+
+			m_Condition.Compile(bc);
+			bc.Leave(m_StackFrame);
+			bc.Jump(OpCode.Jf, start);
+
+			int exitpoint = bc.GetJumpPointForNextInstruction();
+
+			foreach (Instruction i in L.BreakJumps)
+				i.NumVal = exitpoint;
+		}
+
+
 	}
 	}
 }
 }

+ 29 - 0
src/MoonSharp.Interpreter/Tree/Statements/WhileStatement.cs

@@ -3,6 +3,7 @@ using System.Collections.Generic;
 using System.Linq;
 using System.Linq;
 using System.Text;
 using System.Text;
 using MoonSharp.Interpreter.Execution;
 using MoonSharp.Interpreter.Execution;
+using MoonSharp.Interpreter.Execution.VM;
 using MoonSharp.Interpreter.Grammar;
 using MoonSharp.Interpreter.Grammar;
 
 
 namespace MoonSharp.Interpreter.Tree.Statements
 namespace MoonSharp.Interpreter.Tree.Statements
@@ -38,5 +39,33 @@ namespace MoonSharp.Interpreter.Tree.Statements
 			return ExecutionFlow.None;
 			return ExecutionFlow.None;
 		}
 		}
 
 
+		public override void Compile(Chunk bc)
+		{
+			Loop L = new Loop()
+			{
+				Scope = m_StackFrame
+			};
+
+			bc.LoopTracker.Loops.Push(L);
+
+			int start = bc.GetJumpPointForNextInstruction();
+
+			m_Condition.Compile(bc);
+			var jumpend = bc.Jump(OpCode.Jf, -1);
+
+			bc.Enter(m_StackFrame);
+			m_Block.Compile(bc);
+			bc.Debug("..end");
+			bc.Leave(m_StackFrame);
+			bc.Jump(OpCode.Jump, start);
+
+			int exitpoint = bc.GetJumpPointForNextInstruction();
+
+			foreach (Instruction i in L.BreakJumps)
+				i.NumVal = exitpoint;
+
+			jumpend.NumVal = exitpoint;
+		}
+
 	}
 	}
 }
 }

+ 6 - 0
src/MoonSharp/MoonSharp.csproj

@@ -40,6 +40,9 @@
     <ErrorReport>prompt</ErrorReport>
     <ErrorReport>prompt</ErrorReport>
     <WarningLevel>4</WarningLevel>
     <WarningLevel>4</WarningLevel>
   </PropertyGroup>
   </PropertyGroup>
+  <PropertyGroup>
+    <ApplicationIcon>moonsharp256.ico</ApplicationIcon>
+  </PropertyGroup>
   <ItemGroup>
   <ItemGroup>
     <Reference Include="System" />
     <Reference Include="System" />
     <Reference Include="System.Core" />
     <Reference Include="System.Core" />
@@ -61,6 +64,9 @@
   <ItemGroup>
   <ItemGroup>
     <None Include="app.config" />
     <None Include="app.config" />
   </ItemGroup>
   </ItemGroup>
+  <ItemGroup>
+    <Content Include="moonsharp256.ico" />
+  </ItemGroup>
   <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
   <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
   <!-- To modify your build process, add your task inside one of the targets below and uncomment it. 
   <!-- To modify your build process, add your task inside one of the targets below and uncomment it. 
        Other similar extension points exist, see Microsoft.Common.targets.
        Other similar extension points exist, see Microsoft.Common.targets.

+ 5 - 5
src/MoonSharp/Program.cs

@@ -31,7 +31,7 @@ namespace MoonSharp
 		[STAThread]
 		[STAThread]
 		static void Main(string[] args)
 		static void Main(string[] args)
 		{
 		{
-			Console.WriteLine("Moon# REPL {0}\nCopyright (C) 2014 Marco Mastropaolo",
+			Console.WriteLine("Moon# {0}\nCopyright (C) 2014 Marco Mastropaolo\nhttp://www.moonsharp.org",
 				Assembly.GetExecutingAssembly().GetName().Version);
 				Assembly.GetExecutingAssembly().GetName().Version);
 
 
 			Console.WriteLine("Based on Lua 5.2, Copyright (C) 1994-2013 Lua.org");
 			Console.WriteLine("Based on Lua 5.2, Copyright (C) 1994-2013 Lua.org");
@@ -40,12 +40,12 @@ namespace MoonSharp
 
 
 			if (args.Length == 1)
 			if (args.Length == 1)
 			{
 			{
-				var script = MoonSharpInterpreter.LoadFromFile(args[0]);
+				Table globalTable = new Table();
+				globalTable[new RValue("print")] = new RValue(new CallbackFunction(Print));
 
 
-				RuntimeScope globalScope = new RuntimeScope();
-				globalScope["print"] = new RValue(new CallbackFunction(Print));
+				var script = MoonSharpInterpreter.LoadFromFile(args[0], globalTable);
 
 
-				script.Execute(globalScope);
+				script.Execute();
 
 
 				Console.WriteLine("Done.");
 				Console.WriteLine("Done.");
 				
 				

+ 2 - 2
src/MoonSharp/Properties/AssemblyInfo.cs

@@ -8,7 +8,7 @@ using System.Runtime.InteropServices;
 [assembly: AssemblyTitle("MoonSharp")]
 [assembly: AssemblyTitle("MoonSharp")]
 [assembly: AssemblyDescription("REPL Interpreter for the MoonSharp language")]
 [assembly: AssemblyDescription("REPL Interpreter for the MoonSharp language")]
 [assembly: AssemblyConfiguration("")]
 [assembly: AssemblyConfiguration("")]
-[assembly: AssemblyCompany("Marco Mastropaolo")]
+[assembly: AssemblyCompany("http://www.moonsharp.org")]
 [assembly: AssemblyProduct("MoonSharp")]
 [assembly: AssemblyProduct("MoonSharp")]
 [assembly: AssemblyCopyright("Copyright ©  2014, Marco Mastropaolo")]
 [assembly: AssemblyCopyright("Copyright ©  2014, Marco Mastropaolo")]
 [assembly: AssemblyTrademark("")]
 [assembly: AssemblyTrademark("")]
@@ -32,5 +32,5 @@ using System.Runtime.InteropServices;
 // You can specify all the values or you can default the Build and Revision Numbers 
 // You can specify all the values or you can default the Build and Revision Numbers 
 // by using the '*' as shown below:
 // by using the '*' as shown below:
 // [assembly: AssemblyVersion("1.0.*")]
 // [assembly: AssemblyVersion("1.0.*")]
-[assembly: AssemblyVersion("0.1.1")]
+[assembly: AssemblyVersion("0.1.8.*")]
 [assembly: AssemblyFileVersion("1.0.0.0")]
 [assembly: AssemblyFileVersion("1.0.0.0")]

BIN
src/MoonSharp/moonsharp256.ico


+ 1 - 1
src/MoonSharpTests/Program.cs

@@ -12,7 +12,7 @@ namespace MoonSharpTests
 {
 {
 	class Program
 	class Program
 	{
 	{
-		public const string RESTRICT_TEST = "TableMethod6";
+		public const string RESTRICT_TEST = "ForEachLoop";
 
 
 		static void Main(string[] args)
 		static void Main(string[] args)
 		{
 		{

+ 1 - 0
src/moonsharp.sln

@@ -26,6 +26,7 @@ Global
 	EndGlobalSection
 	EndGlobalSection
 	GlobalSection(ProjectConfigurationPlatforms) = postSolution
 	GlobalSection(ProjectConfigurationPlatforms) = postSolution
 		{2A4BD262-D6EB-4611-A28B-27B6DAEB089B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
 		{2A4BD262-D6EB-4611-A28B-27B6DAEB089B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+		{2A4BD262-D6EB-4611-A28B-27B6DAEB089B}.Debug|Any CPU.Build.0 = Debug|Any CPU
 		{2A4BD262-D6EB-4611-A28B-27B6DAEB089B}.Release|Any CPU.ActiveCfg = Release|Any CPU
 		{2A4BD262-D6EB-4611-A28B-27B6DAEB089B}.Release|Any CPU.ActiveCfg = Release|Any CPU
 		{91EA9B9D-FE03-4273-BDAF-8AD42EDE1E59}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
 		{91EA9B9D-FE03-4273-BDAF-8AD42EDE1E59}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
 		{91EA9B9D-FE03-4273-BDAF-8AD42EDE1E59}.Debug|Any CPU.Build.0 = Debug|Any CPU
 		{91EA9B9D-FE03-4273-BDAF-8AD42EDE1E59}.Debug|Any CPU.Build.0 = Debug|Any CPU