Xanathar 11 éve
szülő
commit
c699cf09ff
23 módosított fájl, 309 hozzáadás és 232 törlés
  1. 1 12
      src/MoonSharp.Debugger/ValueBrowser.cs
  2. 21 21
      src/MoonSharp.Interpreter/CoreLib/LoadMethods.cs
  3. 5 2
      src/MoonSharp.Interpreter/CoreLib/MetaTableMethods.cs
  4. 0 33
      src/MoonSharp.Interpreter/CoreLib/RawTableAccess.cs
  5. 0 2
      src/MoonSharp.Interpreter/DataTypes/DataType.cs
  6. 8 34
      src/MoonSharp.Interpreter/DataTypes/DynValue.cs
  7. 17 15
      src/MoonSharp.Interpreter/Execution/VM/ByteCode.cs
  8. 13 4
      src/MoonSharp.Interpreter/Execution/VM/Instruction.cs
  9. 4 8
      src/MoonSharp.Interpreter/Execution/VM/OpCode.cs
  10. 2 5
      src/MoonSharp.Interpreter/Execution/VM/Processor/Processor_IExecutionContext.cs
  11. 137 62
      src/MoonSharp.Interpreter/Execution/VM/Processor/Processor_InstructionLoop.cs
  12. 6 6
      src/MoonSharp.Interpreter/Execution/VM/Processor/Processor_UtilityFunctions.cs
  13. 1 2
      src/MoonSharp.Interpreter/Modules/CoreModules.cs
  14. 0 1
      src/MoonSharp.Interpreter/Modules/ModuleRegister.cs
  15. 0 1
      src/MoonSharp.Interpreter/MoonSharp.Interpreter.csproj
  16. 2 1
      src/MoonSharp.Interpreter/Tree/Expressions/FunctionDefinitionExpression.cs
  17. 24 4
      src/MoonSharp.Interpreter/Tree/Expressions/IndexExpression.cs
  18. 5 0
      src/MoonSharp.Interpreter/Tree/Expressions/LiteralExpression.cs
  19. 1 1
      src/MoonSharp.Interpreter/Tree/FunctionCall.cs
  20. 6 7
      src/MoonSharp.Interpreter/Tree/Statements/FunctionDefinitionStatement.cs
  21. 45 2
      src/MoonSharp/Program.cs
  22. 10 9
      src/PerformanceComparison/Program.cs
  23. 1 0
      src/moonsharp.sln

+ 1 - 12
src/MoonSharp.Debugger/ValueBrowser.cs

@@ -90,11 +90,6 @@ namespace MoonSharp.Debugger
 					AddProperty("Count", V.Tuple.Length);
 					AddProperty("Count", V.Tuple.Length);
 					BuildTupleTable(V);
 					BuildTupleTable(V);
 					break;
 					break;
-				case DataType.Symbol:
-					lblData.Text = "SYMBOL / TABLE-REF";
-					txtString.Text = V.String.ToString();
-					BuildSymbolTable(V);
-					break;
 				case DataType.ClrFunction:
 				case DataType.ClrFunction:
 					txtString.Visible = true;
 					txtString.Visible = true;
 					txtString.Text = "Value is a CLR function.";
 					txtString.Text = "Value is a CLR function.";
@@ -131,13 +126,7 @@ namespace MoonSharp.Debugger
 			}
 			}
 		}
 		}
 
 
-		private void BuildSymbolTable(DynValue V)
-		{
-			var S = V.Symbol;
-			lvTableData.Add("Type", S.Type);
-			lvTableData.Add("Index", S.Index);
-			lvTableData.Add("Name", S.Name);
-		}
+
 
 
 		private void BuildFunctionTable(DynValue V)
 		private void BuildFunctionTable(DynValue V)
 		{
 		{

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

@@ -58,27 +58,27 @@ namespace MoonSharp.Interpreter.CoreLib
 		}
 		}
 
 
 
 
-//		[MoonSharpMethod] 
-//		public const string require = @"
-//			function(modulename)
-//				if (package == nil) then package = { }; end
-//				if (package.loaded == nil) then package.loaded = { }; end
-//
-//				local m = package.loaded[modulename];
-//
-//				if (m ~= nil) then
-//					return m;
-//				end
-//
-//				local func = __require_clr_impl(modulename);
-//
-//				local res = func();
-//
-//				package.loaded[modulename] = res;
-//
-//				return res;
-//			end
-//		";
+		[MoonSharpMethod]
+		public const string require = @"
+			function(modulename)
+				if (package == nil) then package = { }; end
+				if (package.loaded == nil) then package.loaded = { }; end
+
+				local m = package.loaded[modulename];
+
+				if (m ~= nil) then
+					return m;
+				end
+
+				local func = __require_clr_impl(modulename);
+
+				local res = func();
+
+				package.loaded[modulename] = res;
+
+				return res;
+			end
+		";
 
 
 
 
 
 

+ 5 - 2
src/MoonSharp.Interpreter/CoreLib/MetaTableMethods.cs

@@ -28,7 +28,7 @@ namespace MoonSharp.Interpreter.CoreLib
 				throw new ScriptRuntimeException(null, "cannot change a protected metatable");
 				throw new ScriptRuntimeException(null, "cannot change a protected metatable");
 			}
 			}
 
 
-			table.Meta = metatable;
+			table.MetaTable = metatable.Table;
 			return table;
 			return table;
 		}
 		}
 
 
@@ -51,7 +51,10 @@ namespace MoonSharp.Interpreter.CoreLib
 				return curmeta;
 				return curmeta;
 			}
 			}
 
 
-			return obj.Meta ?? DynValue.Nil;
+			if (obj.MetaTable != null)
+				return DynValue.NewTable(obj.MetaTable);
+
+			return DynValue.Nil;
 		}
 		}
 
 
 		// rawget (table, index)
 		// rawget (table, index)

+ 0 - 33
src/MoonSharp.Interpreter/CoreLib/RawTableAccess.cs

@@ -1,33 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using MoonSharp.Interpreter.Execution;
-
-namespace MoonSharp.Interpreter.CoreLib
-{
-	[MoonSharpModule]
-	public class RawTableAccess
-	{
-		[MoonSharpMethod]
-		static DynValue rawget(ScriptExecutionContext executionContext, CallbackArguments args)
-		{
-			DynValue table = args.AsType(0, "rawget", DataType.Table);
-			DynValue index = args[1];
-
-			return table.Table[index];
-		}
-
-		[MoonSharpMethod]
-		static DynValue rawset(ScriptExecutionContext executionContext, CallbackArguments args)
-		{
-			DynValue table = args.AsType(0, "rawset", DataType.Table);
-			DynValue index = args[1];
-			DynValue val = args[2];
-
-			table.Table[index] = val;
-
-			return table;
-		}
-	}
-}

+ 0 - 2
src/MoonSharp.Interpreter/DataTypes/DataType.cs

@@ -19,7 +19,6 @@ namespace MoonSharp.Interpreter
 		UserData,
 		UserData,
 		Thread,
 		Thread,
 
 
-		Symbol,
 		ClrFunction,
 		ClrFunction,
 		TailCallRequest,
 		TailCallRequest,
 	}
 	}
@@ -50,7 +49,6 @@ namespace MoonSharp.Interpreter
 					return "thread";
 					return "thread";
 				case DataType.Tuple:
 				case DataType.Tuple:
 				case DataType.TailCallRequest:
 				case DataType.TailCallRequest:
-				case DataType.Symbol:
 				default:
 				default:
 					throw new ScriptRuntimeException(null, "Unexpected LuaType {0}", type);
 					throw new ScriptRuntimeException(null, "Unexpected LuaType {0}", type);
 			}
 			}

+ 8 - 34
src/MoonSharp.Interpreter/DataTypes/DynValue.cs

@@ -54,17 +54,13 @@ namespace MoonSharp.Interpreter
 		/// </summary>
 		/// </summary>
 		public string String { get; private set; }
 		public string String { get; private set; }
 		/// <summary>
 		/// <summary>
-		/// Gets the symbol reference contained in this value (valid only if the <seealso cref="Type"/> is <seealso cref="DataType.Symbol"/>)
-		/// </summary>
-		public SymbolRef Symbol { get; private set; }
-		/// <summary>
 		/// Gets the CLR callback (valid only if the <seealso cref="Type"/> is <seealso cref="DataType.Callback"/>)
 		/// Gets the CLR callback (valid only if the <seealso cref="Type"/> is <seealso cref="DataType.Callback"/>)
 		/// </summary>
 		/// </summary>
 		public CallbackFunction Callback { get; set; }
 		public CallbackFunction Callback { get; set; }
 		/// <summary>
 		/// <summary>
 		/// Gets the meta-table associated with this instance.
 		/// Gets the meta-table associated with this instance.
 		/// </summary>
 		/// </summary>
-		public DynValue Meta { get; set; }
+		public Table MetaTable { get; set; }
 		/// <summary>
 		/// <summary>
 		/// Gets or sets the user object, if this value is userdata
 		/// Gets or sets the user object, if this value is userdata
 		/// </summary>
 		/// </summary>
@@ -109,18 +105,6 @@ namespace MoonSharp.Interpreter
 			};
 			};
 		}
 		}
 
 
-		/// <summary>
-		/// Creates a new writable value initialized to the specified symbol reference.
-		/// </summary>
-		public static DynValue NewReference(SymbolRef symbol)
-		{
-			return new DynValue()
-			{
-				Symbol = symbol,
-				Type = DataType.Symbol,
-			};
-		}
-
 		/// <summary>
 		/// <summary>
 		/// Creates a new writable value initialized to the specified string.
 		/// Creates a new writable value initialized to the specified string.
 		/// </summary>
 		/// </summary>
@@ -204,7 +188,7 @@ namespace MoonSharp.Interpreter
 		{
 		{
 			return new DynValue()
 			return new DynValue()
 			{
 			{
-				Meta = tailFn,
+				UserObject = tailFn,
 				Tuple = args,
 				Tuple = args,
 				Type = DataType.TailCallRequest,
 				Type = DataType.TailCallRequest,
 			};
 			};
@@ -274,13 +258,13 @@ namespace MoonSharp.Interpreter
 		/// </summary>
 		/// </summary>
 		/// <param name="obj">The CLR object.</param>
 		/// <param name="obj">The CLR object.</param>
 		/// <param name="metatable">Optional - the metatable.</param>
 		/// <param name="metatable">Optional - the metatable.</param>
-		public static DynValue NewObject(object obj, DynValue metatable = null)
+		public static DynValue NewObject(object obj, Table metatable = null)
 		{
 		{
 			return new DynValue()
 			return new DynValue()
 			{
 			{
 				UserObject = obj,
 				UserObject = obj,
 				Type = DataType.UserData,
 				Type = DataType.UserData,
-				Meta = metatable
+				MetaTable = metatable
 			};
 			};
 		}
 		}
 
 
@@ -307,9 +291,6 @@ namespace MoonSharp.Interpreter
 		/// <exception cref="System.ArgumentException">Can't clone Symbol values</exception>
 		/// <exception cref="System.ArgumentException">Can't clone Symbol values</exception>
 		public DynValue Clone()
 		public DynValue Clone()
 		{
 		{
-			if (this.Type == DataType.Symbol)
-				throw new ArgumentException("Can't clone Symbol values");
-
 			DynValue v = new DynValue();
 			DynValue v = new DynValue();
 			v.Boolean = this.Boolean;
 			v.Boolean = this.Boolean;
 			v.Callback = this.Callback;
 			v.Callback = this.Callback;
@@ -320,7 +301,7 @@ namespace MoonSharp.Interpreter
 			v.Table = this.Table;
 			v.Table = this.Table;
 			v.Tuple = this.Tuple;
 			v.Tuple = this.Tuple;
 			v.Type = this.Type;
 			v.Type = this.Type;
-			v.Meta = this.Meta;
+			v.MetaTable = this.MetaTable;
 			v.m_HashCode = this.m_HashCode;
 			v.m_HashCode = this.m_HashCode;
 			return v;
 			return v;
 		}
 		}
@@ -331,9 +312,6 @@ namespace MoonSharp.Interpreter
 		/// <exception cref="System.ArgumentException">Can't clone Symbol values</exception>
 		/// <exception cref="System.ArgumentException">Can't clone Symbol values</exception>
 		public DynValue CloneAsWritable()
 		public DynValue CloneAsWritable()
 		{
 		{
-			if (this.Type == DataType.Symbol)
-				throw new ArgumentException("Can't clone Symbol values");
-
 			DynValue v = new DynValue();
 			DynValue v = new DynValue();
 			v.Boolean = this.Boolean;
 			v.Boolean = this.Boolean;
 			v.Function = this.Function;
 			v.Function = this.Function;
@@ -344,7 +322,7 @@ namespace MoonSharp.Interpreter
 			v.Table = this.Table;
 			v.Table = this.Table;
 			v.Tuple = this.Tuple;
 			v.Tuple = this.Tuple;
 			v.Type = this.Type;
 			v.Type = this.Type;
-			v.Meta = this.Meta;
+			v.MetaTable = this.MetaTable;
 			v.m_HashCode = this.m_HashCode;
 			v.m_HashCode = this.m_HashCode;
 			return v;
 			return v;
 		}
 		}
@@ -385,8 +363,6 @@ namespace MoonSharp.Interpreter
 					return "(Table)";
 					return "(Table)";
 				case DataType.Tuple:
 				case DataType.Tuple:
 					return string.Join("\t", Tuple.Select(t => t.ToPrintString()).ToArray());
 					return string.Join("\t", Tuple.Select(t => t.ToPrintString()).ToArray());
-				case DataType.Symbol:
-					return "(Symbol -- INTERNAL!)";
 				case DataType.TailCallRequest:
 				case DataType.TailCallRequest:
 					return "(TailCallRequest -- INTERNAL!)";
 					return "(TailCallRequest -- INTERNAL!)";
 				case DataType.UserData:
 				case DataType.UserData:
@@ -426,8 +402,6 @@ namespace MoonSharp.Interpreter
 					return string.Join(", ", Tuple.Select(t => t.ToString()).ToArray());
 					return string.Join(", ", Tuple.Select(t => t.ToString()).ToArray());
 				case DataType.TailCallRequest:
 				case DataType.TailCallRequest:
 					return "Tail:(" + string.Join(", ", Tuple.Select(t => t.ToString()).ToArray()) + ")";
 					return "Tail:(" + string.Join(", ", Tuple.Select(t => t.ToString()).ToArray()) + ")";
-				case DataType.Symbol:
-					return Symbol.ToString();
 				case DataType.UserData:
 				case DataType.UserData:
 					return "(UserData)";
 					return "(UserData)";
 				case DataType.Thread:
 				case DataType.Thread:
@@ -501,7 +475,7 @@ namespace MoonSharp.Interpreter
 			if (other == null) return false;
 			if (other == null) return false;
 			if (other.Type != this.Type) return false;
 			if (other.Type != this.Type) return false;
 
 
-			if (other.Meta != this.Meta) return false;
+			if (other.MetaTable != this.MetaTable) return false;
 
 
 			switch (Type)
 			switch (Type)
 			{
 			{
@@ -614,7 +588,7 @@ namespace MoonSharp.Interpreter
 			this.Table = value.Table;
 			this.Table = value.Table;
 			this.Tuple = value.Tuple;
 			this.Tuple = value.Tuple;
 			this.Type = value.Type;
 			this.Type = value.Type;
-			this.Meta = value.Meta;
+			this.MetaTable = value.MetaTable;
 			this.m_HashCode = -1;
 			this.m_HashCode = -1;
 		}
 		}
 
 

+ 17 - 15
src/MoonSharp.Interpreter/Execution/VM/ByteCode.cs

@@ -48,6 +48,11 @@ namespace MoonSharp.Interpreter.Execution.VM
 			return Code.Count - 1;
 			return Code.Count - 1;
 		}
 		}
 
 
+		public Instruction GetLastInstruction()
+		{
+			return Code[Code.Count - 1];
+		}
+
 		private Instruction AppendInstruction(Instruction c)
 		private Instruction AppendInstruction(Instruction c)
 		{
 		{
 			Code.Add(c);
 			Code.Add(c);
@@ -72,7 +77,6 @@ namespace MoonSharp.Interpreter.Execution.VM
 		public void Emit_Call(int argCount)
 		public void Emit_Call(int argCount)
 		{
 		{
 			AppendInstruction(new Instruction() { OpCode = OpCode.Call, NumVal = argCount });
 			AppendInstruction(new Instruction() { OpCode = OpCode.Call, NumVal = argCount });
-			AppendInstruction(new Instruction() { OpCode = OpCode.TailChk });
 		}
 		}
 
 
 
 
@@ -190,15 +194,14 @@ namespace MoonSharp.Interpreter.Execution.VM
 			switch (sym.Type)
 			switch (sym.Type)
 			{
 			{
 				case SymbolRefType.Global:
 				case SymbolRefType.Global:
-					AppendInstruction(new Instruction() { OpCode = OpCode.Global });
-					Emit_Literal(DynValue.NewString(sym.i_Name));
-					AppendInstruction(new Instruction() { OpCode = OpCode.LoadIdx });
-					return 3;
+					AppendInstruction(new Instruction() { OpCode = OpCode.PushEnv });
+					AppendInstruction(new Instruction() { OpCode = OpCode.Index, Value = DynValue.NewString(sym.i_Name) });
+					return 2;
 				case SymbolRefType.Local:
 				case SymbolRefType.Local:
-					AppendInstruction(new Instruction() { OpCode = OpCode.LoadLcl, Symbol = sym });
+					AppendInstruction(new Instruction() { OpCode = OpCode.Local, Symbol = sym });
 					return 1;
 					return 1;
 				case SymbolRefType.Upvalue:
 				case SymbolRefType.Upvalue:
-					AppendInstruction(new Instruction() { OpCode = OpCode.LoadUpv, Symbol = sym });
+					AppendInstruction(new Instruction() { OpCode = OpCode.Upvalue, Symbol = sym });
 					return 1;
 					return 1;
 				default:
 				default:
 					throw new InternalErrorException("Unexpected symbol type : {0}", sym);
 					throw new InternalErrorException("Unexpected symbol type : {0}", sym);
@@ -210,10 +213,9 @@ namespace MoonSharp.Interpreter.Execution.VM
 			switch (sym.Type)
 			switch (sym.Type)
 			{
 			{
 				case SymbolRefType.Global:
 				case SymbolRefType.Global:
-					AppendInstruction(new Instruction() { OpCode = OpCode.Global });
-					Emit_Literal(DynValue.NewString(sym.i_Name));
-					AppendInstruction(new Instruction() { OpCode = OpCode.StoreIdx, Symbol = sym, NumVal = stackofs, NumVal2 = tupleidx });
-					return 3;
+					AppendInstruction(new Instruction() { OpCode = OpCode.PushEnv });
+					AppendInstruction(new Instruction() { OpCode = OpCode.IndexSet, Symbol = sym, NumVal = stackofs, NumVal2 = tupleidx, Value = DynValue.NewString(sym.i_Name) });
+					return 2;
 				case SymbolRefType.Local:
 				case SymbolRefType.Local:
 					AppendInstruction(new Instruction() { OpCode = OpCode.StoreLcl, Symbol = sym, NumVal = stackofs, NumVal2 = tupleidx });
 					AppendInstruction(new Instruction() { OpCode = OpCode.StoreLcl, Symbol = sym, NumVal = stackofs, NumVal2 = tupleidx });
 					return 1;
 					return 1;
@@ -235,14 +237,14 @@ namespace MoonSharp.Interpreter.Execution.VM
 			return AppendInstruction(new Instruction() { OpCode = OpCode.TblInitI });
 			return AppendInstruction(new Instruction() { OpCode = OpCode.TblInitI });
 		}
 		}
 
 
-		public Instruction Emit_LoadIdx()
+		public Instruction Emit_Index(DynValue index = null)
 		{
 		{
-			return AppendInstruction(new Instruction() { OpCode = OpCode.LoadIdx });
+			return AppendInstruction(new Instruction() { OpCode = OpCode.Index, Value = index });
 		}
 		}
 
 
-		public Instruction Emit_StoreIdx(int stackofs, int tupleidx)
+		public Instruction Emit_IndexSet(int stackofs, int tupleidx, DynValue index = null)
 		{
 		{
-			return AppendInstruction(new Instruction() { OpCode = OpCode.StoreIdx, NumVal = stackofs, NumVal2 = tupleidx });
+			return AppendInstruction(new Instruction() { OpCode = OpCode.IndexSet, NumVal = stackofs, NumVal2 = tupleidx, Value = index });
 		}
 		}
 
 
 		public Instruction Emit_Copy(int numval)
 		public Instruction Emit_Copy(int numval)

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

@@ -39,8 +39,12 @@ namespace MoonSharp.Interpreter.Execution.VM
 				case OpCode.Debug:
 				case OpCode.Debug:
 					return string.Format("[[ {0} ]]", Name);
 					return string.Format("[[ {0} ]]", Name);
 				case OpCode.Literal:
 				case OpCode.Literal:
+				case OpCode.Index:
 					append = string.Format("{0}{1}", GenSpaces(), PurifyFromNewLines(Value));
 					append = string.Format("{0}{1}", GenSpaces(), PurifyFromNewLines(Value));
 					break;
 					break;
+				case OpCode.IndexSet:
+					append = string.Format("{0}{1} <- {2}:{3}", GenSpaces(), PurifyFromNewLines(Value), NumVal, NumVal2);
+					break;
 				case OpCode.Nop:
 				case OpCode.Nop:
 					append = string.Format("{0}#{1}", GenSpaces(), Name);
 					append = string.Format("{0}#{1}", GenSpaces(), Name);
 					break;
 					break;
@@ -50,19 +54,21 @@ namespace MoonSharp.Interpreter.Execution.VM
 				case OpCode.ExpTuple:
 				case OpCode.ExpTuple:
 				case OpCode.Incr:
 				case OpCode.Incr:
 				case OpCode.Pop:
 				case OpCode.Pop:
+				case OpCode.Copy:
 					append = string.Format("{0}{1}", GenSpaces(), NumVal);
 					append = string.Format("{0}{1}", GenSpaces(), NumVal);
 					break;
 					break;
+				case OpCode.Swap:
+					append = string.Format("{0}{1},{2}", GenSpaces(), NumVal, NumVal2);
+					break;
 				case OpCode.BeginFn:
 				case OpCode.BeginFn:
 					append = string.Format("{0}{1}:{2},{3}", GenSpaces(), Name, NumVal, NumVal2);
 					append = string.Format("{0}{1}:{2},{3}", GenSpaces(), Name, NumVal, NumVal2);
 					break;
 					break;
-				case OpCode.TMP_Load:
-				case OpCode.LoadLcl:
-				case OpCode.LoadUpv:
+				case OpCode.Local:
+				case OpCode.Upvalue:
 					append = string.Format("{0}{1}", GenSpaces(), Symbol);
 					append = string.Format("{0}{1}", GenSpaces(), Symbol);
 					break;
 					break;
 				case OpCode.StoreUpv:
 				case OpCode.StoreUpv:
 				case OpCode.StoreLcl:
 				case OpCode.StoreLcl:
-				case OpCode.TMP_Store:
 					append = string.Format("{0}{1} <- {2}:{3}", GenSpaces(), Symbol, NumVal, NumVal2);
 					append = string.Format("{0}{1} <- {2}:{3}", GenSpaces(), Symbol, NumVal, NumVal2);
 					break;
 					break;
 				case OpCode.JtOrPop:
 				case OpCode.JtOrPop:
@@ -93,6 +99,9 @@ namespace MoonSharp.Interpreter.Execution.VM
 
 
 		private string PurifyFromNewLines(DynValue Value)
 		private string PurifyFromNewLines(DynValue Value)
 		{
 		{
+			if (Value == null)
+				return "";
+
 			return Value.ToString().Replace('\n', ' ').Replace('\r', ' ');
 			return Value.ToString().Replace('\n', ' ').Replace('\r', ' ');
 		}
 		}
 
 

+ 4 - 8
src/MoonSharp.Interpreter/Execution/VM/OpCode.cs

@@ -23,14 +23,11 @@ namespace MoonSharp.Interpreter.Execution.VM
 		TblInitN,	// Initializes a table named entry
 		TblInitN,	// Initializes a table named entry
 		TblInitI,	// Initializes a table positional entry
 		TblInitI,	// Initializes a table positional entry
 
 
-		TMP_Load,
-		TMP_Store,
+		PushEnv,	// Pushes the current ENV table on the stack
 
 
-		Global,
-
-		StoreLcl, LoadLcl,
-		StoreUpv, LoadUpv,
-		StoreIdx, LoadIdx, 
+		StoreLcl, Local,
+		StoreUpv, Upvalue,
+		IndexSet, Index, 
 
 
 		// Stack-frame ops and calls
 		// Stack-frame ops and calls
 		Enter,		// Enters a new stack frame
 		Enter,		// Enters a new stack frame
@@ -40,7 +37,6 @@ namespace MoonSharp.Interpreter.Execution.VM
 		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.
 		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.
 		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.
-		TailChk,	// Checks if the return value from a Ret or Clr call is a tail call request, in case it repeats the call 
 
 
 		// Jumps
 		// Jumps
 		Jump,		// Jumps to the specified PC
 		Jump,		// Jumps to the specified PC

+ 2 - 5
src/MoonSharp.Interpreter/Execution/VM/Processor/Processor_IExecutionContext.cs

@@ -24,13 +24,10 @@ namespace MoonSharp.Interpreter.Execution.VM
 
 
 		internal DynValue GetMetamethod(DynValue value, string metamethod)
 		internal DynValue GetMetamethod(DynValue value, string metamethod)
 		{
 		{
-			if (value.Meta == null || value.Type == DataType.Nil)
+			if (value.MetaTable == null || value.Type == DataType.Nil)
 				return null;
 				return null;
 
 
-			if (value.Meta.Type != DataType.Table)
-				throw new InternalErrorException("Metatable is not a table!");
-
-			var metameth = value.Meta.Table.RawGet(metamethod);
+			var metameth = value.MetaTable.RawGet(metamethod);
 			
 			
 			if (metameth == null || metameth.Type == DataType.Nil)
 			if (metameth == null || metameth.Type == DataType.Nil)
 				return null;
 				return null;

+ 137 - 62
src/MoonSharp.Interpreter/Execution/VM/Processor/Processor_InstructionLoop.cs

@@ -78,9 +78,6 @@ namespace MoonSharp.Interpreter.Execution.VM
 					case OpCode.Call:
 					case OpCode.Call:
 						instructionPtr = Internal_ExecCall(i.NumVal, instructionPtr);
 						instructionPtr = Internal_ExecCall(i.NumVal, instructionPtr);
 						break;
 						break;
-					case OpCode.TailChk:
-						instructionPtr = ExecTailChk(i, instructionPtr);
-						break;
 					case OpCode.Scalar:
 					case OpCode.Scalar:
 						m_ValueStack.Push(m_ValueStack.Pop().ToScalar());
 						m_ValueStack.Push(m_ValueStack.Pop().ToScalar());
 						break;
 						break;
@@ -153,18 +150,17 @@ namespace MoonSharp.Interpreter.Execution.VM
 					case OpCode.ExpTuple:
 					case OpCode.ExpTuple:
 						ExecExpTuple(i);
 						ExecExpTuple(i);
 						break;
 						break;
-					case OpCode.TMP_Load:
-					case OpCode.LoadLcl:
-					case OpCode.LoadUpv:
-						m_ValueStack.Push(this.GetGenericSymbol(i.Symbol));
+					case OpCode.Local:
+						m_ValueStack.Push(m_ExecutionStack.Peek().LocalScope[i.Symbol.i_Index]);
+						break;
+					case OpCode.Upvalue:
+						m_ValueStack.Push(m_ExecutionStack.Peek().ClosureScope[i.Symbol.i_Index]);
 						break;
 						break;
 					case OpCode.StoreUpv:
 					case OpCode.StoreUpv:
+						ExecStoreUpv(i);
+						break;
 					case OpCode.StoreLcl:
 					case OpCode.StoreLcl:
-					case OpCode.TMP_Store:
-						{
-							DynValue v = GetStoreValue(i);
-							AssignGenericSymbol(i.Symbol, v);
-						}
+						ExecStoreLcl(i);
 						break;
 						break;
 					case OpCode.TblInitN:
 					case OpCode.TblInitN:
 						ExecTblInitN(i);
 						ExecTblInitN(i);
@@ -172,14 +168,14 @@ namespace MoonSharp.Interpreter.Execution.VM
 					case OpCode.TblInitI:
 					case OpCode.TblInitI:
 						ExecTblInitI(i);
 						ExecTblInitI(i);
 						break;
 						break;
-					case OpCode.LoadIdx:
-						instructionPtr = ExecLoadIdx(i, instructionPtr);
+					case OpCode.Index:
+						instructionPtr = ExecIndex(i, instructionPtr);
 						break;
 						break;
-					case OpCode.Global:
+					case OpCode.PushEnv:
 						m_ValueStack.Push(DynValue.NewTable(m_GlobalTable));
 						m_ValueStack.Push(DynValue.NewTable(m_GlobalTable));
 						break;
 						break;
-					case OpCode.StoreIdx:
-						instructionPtr = ExecStoreIdx(i, instructionPtr);
+					case OpCode.IndexSet:
+						instructionPtr = ExecIndexSet(i, instructionPtr);
 						break;
 						break;
 					case OpCode.Invalid:
 					case OpCode.Invalid:
 						throw new NotImplementedException(string.Format("Invalid opcode : {0}", i.Name));
 						throw new NotImplementedException(string.Format("Invalid opcode : {0}", i.Name));
@@ -199,6 +195,40 @@ namespace MoonSharp.Interpreter.Execution.VM
 
 
 		}
 		}
 
 
+
+		private void AssignLocal(SymbolRef symref, DynValue value)
+		{
+			var stackframe = m_ExecutionStack.Peek();
+
+			DynValue v = stackframe.LocalScope[symref.i_Index];
+			if (v == null)
+				stackframe.LocalScope[symref.i_Index] = v = DynValue.NewNil();
+
+			v.Assign(value);
+		}
+
+		private void ExecStoreLcl(Instruction i)
+		{
+			DynValue value = GetStoreValue(i);
+			SymbolRef symref = i.Symbol;
+
+			AssignLocal(symref, value);
+		}
+
+		private void ExecStoreUpv(Instruction i)
+		{
+			DynValue value = GetStoreValue(i);
+			SymbolRef symref = i.Symbol;
+
+			var stackframe = m_ExecutionStack.Peek();
+
+			DynValue v = stackframe.ClosureScope[symref.i_Index];
+			if (v == null)
+				stackframe.ClosureScope[symref.i_Index] = v = DynValue.NewNil();
+
+			v.Assign(value);
+		}
+
 		private void ExecSwap(Instruction i)
 		private void ExecSwap(Instruction i)
 		{
 		{
 			DynValue v1 = m_ValueStack.Peek(i.NumVal);
 			DynValue v1 = m_ValueStack.Peek(i.NumVal);
@@ -353,30 +383,6 @@ namespace MoonSharp.Interpreter.Execution.VM
 		}
 		}
 
 
 
 
-		private int ExecRet(Instruction i)
-		{
-			if (i.NumVal == 0)
-			{
-				int retpoint = PopToBasePointer();
-				var argscnt = (int)(m_ValueStack.Pop().Number);
-				m_ValueStack.RemoveLast(argscnt + 1);
-				m_ValueStack.Push(DynValue.Nil);
-				return retpoint;
-			}
-			else if (i.NumVal == 1)
-			{
-				var retval = m_ValueStack.Pop();
-				int retpoint = PopToBasePointer();
-				var argscnt = (int)(m_ValueStack.Pop().Number);
-				m_ValueStack.RemoveLast(argscnt + 1);
-				m_ValueStack.Push(retval);
-				return retpoint;
-			}
-			else
-			{
-				throw new InternalErrorException("RET supports only 0 and 1 ret val scenarios");
-			}
-		}
 
 
 		private void ExecBeginFn(Instruction i)
 		private void ExecBeginFn(Instruction i)
 		{
 		{
@@ -417,7 +423,7 @@ namespace MoonSharp.Interpreter.Execution.VM
 			{
 			{
 				if (i >= numargs)
 				if (i >= numargs)
 				{
 				{
-					this.AssignGenericSymbol(I.SymbolList[i], DynValue.NewNil());
+					this.AssignLocal(I.SymbolList[i], DynValue.NewNil());
 				}
 				}
 				else if ((i == I.SymbolList.Length - 1) && (I.SymbolList[i].i_Name == "..."))
 				else if ((i == I.SymbolList.Length - 1) && (I.SymbolList[i].i_Name == "..."))
 				{
 				{
@@ -429,16 +435,17 @@ namespace MoonSharp.Interpreter.Execution.VM
 						varargs[ii] = m_ValueStack.Peek(numargs - i - ii).CloneAsWritable();
 						varargs[ii] = m_ValueStack.Peek(numargs - i - ii).CloneAsWritable();
 					}
 					}
 
 
-					this.AssignGenericSymbol(I.SymbolList[i], DynValue.NewTuple(varargs));
+					this.AssignLocal(I.SymbolList[i], DynValue.NewTuple(varargs));
 				}
 				}
 				else
 				else
 				{
 				{
-					this.AssignGenericSymbol(I.SymbolList[i], m_ValueStack.Peek(numargs - i).CloneAsWritable());
+					this.AssignLocal(I.SymbolList[i], m_ValueStack.Peek(numargs - i).CloneAsWritable());
 				}
 				}
 			}
 			}
 		}
 		}
 
 
 
 
+
 		private int Internal_ExecCall(int argsCount, int instructionPtr)
 		private int Internal_ExecCall(int argsCount, int instructionPtr)
 		{
 		{
 			DynValue fn = m_ValueStack.Peek(argsCount);
 			DynValue fn = m_ValueStack.Peek(argsCount);
@@ -449,7 +456,8 @@ namespace MoonSharp.Interpreter.Execution.VM
 				var ret = fn.Callback.Invoke(new ScriptExecutionContext(this, fn.Callback), args);
 				var ret = fn.Callback.Invoke(new ScriptExecutionContext(this, fn.Callback), args);
 				m_ValueStack.RemoveLast(argsCount + 1);
 				m_ValueStack.RemoveLast(argsCount + 1);
 				m_ValueStack.Push(ret);
 				m_ValueStack.Push(ret);
-				return instructionPtr;
+
+				return ExecTailChk(null, instructionPtr);
 			}
 			}
 			else if (fn.Type == DataType.Function)
 			else if (fn.Type == DataType.Function)
 			{
 			{
@@ -465,9 +473,9 @@ namespace MoonSharp.Interpreter.Execution.VM
 			}
 			}
 			else
 			else
 			{
 			{
-				if (fn.Meta != null)
+				if (fn.MetaTable != null)
 				{
 				{
-					var m = fn.Meta.Table.RawGet("__call");
+					var m = fn.MetaTable.RawGet("__call");
 
 
 					if (m != null && m.Type != DataType.Nil)
 					if (m != null && m.Type != DataType.Nil)
 					{
 					{
@@ -489,6 +497,32 @@ namespace MoonSharp.Interpreter.Execution.VM
 		}
 		}
 
 
 
 
+		private int ExecRet(Instruction i)
+		{
+			int retpoint = 0;
+
+			if (i.NumVal == 0)
+			{
+				retpoint = PopToBasePointer();
+				var argscnt = (int)(m_ValueStack.Pop().Number);
+				m_ValueStack.RemoveLast(argscnt + 1);
+				m_ValueStack.Push(DynValue.Nil);
+				return retpoint;
+			}
+			else if (i.NumVal == 1)
+			{
+				var retval = m_ValueStack.Pop();
+				retpoint = PopToBasePointer();
+				var argscnt = (int)(m_ValueStack.Pop().Number);
+				m_ValueStack.RemoveLast(argscnt + 1);
+				m_ValueStack.Push(retval);
+				return ExecTailChk(i, retpoint);
+			}
+			else
+			{
+				throw new InternalErrorException("RET supports only 0 and 1 ret val scenarios");
+			}
+		}
 
 
 		private int ExecTailChk(Instruction i, int instructionPtr)
 		private int ExecTailChk(Instruction i, int instructionPtr)
 		{
 		{
@@ -498,12 +532,12 @@ namespace MoonSharp.Interpreter.Execution.VM
 			{
 			{
 				m_ValueStack.Pop(); // discard tail call request
 				m_ValueStack.Pop(); // discard tail call request
 
 
-				m_ValueStack.Push(tail.Meta);
+				m_ValueStack.Push((DynValue)tail.UserObject);
 
 
 				for (int ii = 0; ii < tail.Tuple.Length; ii++)
 				for (int ii = 0; ii < tail.Tuple.Length; ii++)
 					m_ValueStack.Push(tail.Tuple[ii]);
 					m_ValueStack.Push(tail.Tuple[ii]);
 
 
-				instructionPtr -= 1;
+				//instructionPtr -= 1;
 				return Internal_ExecCall(tail.Tuple.Length, instructionPtr);
 				return Internal_ExecCall(tail.Tuple.Length, instructionPtr);
 			}
 			}
 
 
@@ -701,7 +735,7 @@ namespace MoonSharp.Interpreter.Execution.VM
 			{
 			{
 				m_ValueStack.Push(DynValue.False);
 				m_ValueStack.Push(DynValue.False);
 			}
 			}
-			else if ((l.Type == DataType.Table || l.Type == DataType.UserData) && (l.Meta != null) && (l.Meta == r.Meta))
+			else if ((l.Type == DataType.Table || l.Type == DataType.UserData) && (l.MetaTable != null) && (l.MetaTable == r.MetaTable))
 			{
 			{
 				int ip = Internal_InvokeBinaryMetaMethod(l, r, "__eq", instructionPtr);
 				int ip = Internal_InvokeBinaryMetaMethod(l, r, "__eq", instructionPtr);
 				if (ip < 0)
 				if (ip < 0)
@@ -841,10 +875,10 @@ namespace MoonSharp.Interpreter.Execution.VM
 			tbl.Table[key] = val.ToScalar();
 			tbl.Table[key] = val.ToScalar();
 		}
 		}
 
 
-		private int ExecStoreIdx(Instruction i, int instructionPtr)
+		private int ExecIndexSet(Instruction i, int instructionPtr)
 		{
 		{
 			// stack: vals.. - base - index
 			// stack: vals.. - base - index
-			DynValue idx = m_ValueStack.Pop();
+			DynValue idx = i.Value ?? m_ValueStack.Pop();
 			DynValue obj = m_ValueStack.Pop();
 			DynValue obj = m_ValueStack.Pop();
 			var v = GetStoreValue(i);
 			var v = GetStoreValue(i);
 
 
@@ -859,22 +893,63 @@ namespace MoonSharp.Interpreter.Execution.VM
 			}
 			}
 		}
 		}
 
 
-		private int ExecLoadIdx(Instruction i, int instructionPtr)
+		private int ExecIndex(Instruction i, int instructionPtr)
 		{
 		{
+			int nestedMetaOps = 100; // sanity check, to avoid potential infinite loop here
+
 			// stack: base - index
 			// stack: base - index
-			DynValue idx = m_ValueStack.Pop();
+			DynValue idx = i.Value ?? m_ValueStack.Pop();
 			DynValue obj = m_ValueStack.Pop();
 			DynValue obj = m_ValueStack.Pop();
 
 
-			if (obj.Type == DataType.Table)
-			{
-				var v = obj.Table[idx];
-				m_ValueStack.Push(v);
-				return instructionPtr;
-			}
-			else
+			DynValue h = null;
+
+			while (nestedMetaOps > 0)
 			{
 			{
-				throw new NotImplementedException();
+				--nestedMetaOps;
+
+				if (obj.Type == DataType.Table)
+				{
+					var v = obj.Table[idx];
+
+					if (!v.IsNil())
+					{
+						m_ValueStack.Push(v);
+						return instructionPtr;
+					}
+
+					if (obj.MetaTable != null)
+						h = obj.MetaTable.RawGet("__index");
+
+					if (h == null || h.IsNil())
+					{
+						m_ValueStack.Push(DynValue.NewNil());
+						return instructionPtr;
+					}
+				}
+				else
+				{
+					if (obj.MetaTable != null)
+						h = obj.MetaTable.RawGet("__index");
+
+					if (h == null || h.IsNil())
+						throw new ScriptRuntimeException("Can't index non table: {0}", obj);
+				}
+
+				if (h.Type == DataType.Function)
+				{
+					m_ValueStack.Push(h);
+					m_ValueStack.Push(obj);
+					m_ValueStack.Push(idx);
+					return Internal_ExecCall(2, instructionPtr);
+				}
+				else
+				{
+					obj = h;
+					h = null;
+				}
 			}
 			}
+
+			throw new ScriptRuntimeException("__index returning too many nested tables");
 		}
 		}
 
 
 
 

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

@@ -53,9 +53,9 @@ namespace MoonSharp.Interpreter.Execution.VM
 		{
 		{
 			DynValue m = null;
 			DynValue m = null;
 
 
-			if (op1.Meta != null)
+			if (op1.MetaTable != null)
 			{
 			{
-				DynValue meta1 = op1.Meta.Table.RawGet(eventName);
+				DynValue meta1 = op1.MetaTable.RawGet(eventName);
 				if (meta1 != null && meta1.Type != DataType.Nil)
 				if (meta1 != null && meta1.Type != DataType.Nil)
 					m = meta1;
 					m = meta1;
 			}
 			}
@@ -90,15 +90,15 @@ namespace MoonSharp.Interpreter.Execution.VM
 
 
 		private DynValue Internal_GetBinHandler(DynValue op1, DynValue op2, string eventName)
 		private DynValue Internal_GetBinHandler(DynValue op1, DynValue op2, string eventName)
 		{
 		{
-			if (op1.Meta != null)
+			if (op1.MetaTable != null)
 			{
 			{
-				DynValue meta1 = op1.Meta.Table.RawGet(eventName);
+				DynValue meta1 = op1.MetaTable.RawGet(eventName);
 				if (meta1 != null && meta1.Type != DataType.Nil)
 				if (meta1 != null && meta1.Type != DataType.Nil)
 					return meta1;
 					return meta1;
 			}
 			}
-			if (op2.Meta != null)
+			if (op2.MetaTable != null)
 			{
 			{
-				DynValue meta2 = op2.Meta.Table.RawGet(eventName);
+				DynValue meta2 = op2.MetaTable.RawGet(eventName);
 				if (meta2 != null && meta2.Type != DataType.Nil)
 				if (meta2 != null && meta2.Type != DataType.Nil)
 					return meta2;
 					return meta2;
 			}
 			}

+ 1 - 2
src/MoonSharp.Interpreter/Modules/CoreModules.cs

@@ -14,13 +14,12 @@ namespace MoonSharp.Interpreter
 		String = 0x8,
 		String = 0x8,
 		LoadMethods = 0x10,
 		LoadMethods = 0x10,
 		Table = 0x20,
 		Table = 0x20,
-		RawTableAccess = 0x40,
 
 
 
 
 
 
 		Preset_HardSandbox = GlobalConsts | TableIterators | String | Table,
 		Preset_HardSandbox = GlobalConsts | TableIterators | String | Table,
 		Preset_SoftSandbox = Preset_HardSandbox | Metatables,
 		Preset_SoftSandbox = Preset_HardSandbox | Metatables,
-		Preset_Default = Preset_SoftSandbox | LoadMethods | RawTableAccess,
+		Preset_Default = Preset_SoftSandbox | LoadMethods ,
 		Preset_Complete = Preset_Default,
 		Preset_Complete = Preset_Default,
 
 
 	}
 	}

+ 0 - 1
src/MoonSharp.Interpreter/Modules/ModuleRegister.cs

@@ -19,7 +19,6 @@ namespace MoonSharp.Interpreter
 			if (modules.Has(CoreModules.LoadMethods)) RegisterModuleType<LoadMethods>(table);
 			if (modules.Has(CoreModules.LoadMethods)) RegisterModuleType<LoadMethods>(table);
 			if (modules.Has(CoreModules.Table)) RegisterModuleType<TableModule>(table);
 			if (modules.Has(CoreModules.Table)) RegisterModuleType<TableModule>(table);
 			if (modules.Has(CoreModules.Table)) RegisterModuleType<TableModule_Globals>(table);
 			if (modules.Has(CoreModules.Table)) RegisterModuleType<TableModule_Globals>(table);
-			if (modules.Has(CoreModules.RawTableAccess)) RegisterModuleType<RawTableAccess>(table);
 
 
 			return table;
 			return table;
 		}
 		}

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

@@ -89,7 +89,6 @@
     <Compile Include="CoreLib\Patterns\PatternMatching.cs">
     <Compile Include="CoreLib\Patterns\PatternMatching.cs">
       <SubType>Code</SubType>
       <SubType>Code</SubType>
     </Compile>
     </Compile>
-    <Compile Include="CoreLib\RawTableAccess.cs" />
     <Compile Include="CoreLib\StringModule.cs" />
     <Compile Include="CoreLib\StringModule.cs" />
     <Compile Include="CoreLib\TableIterators.cs" />
     <Compile Include="CoreLib\TableIterators.cs" />
     <Compile Include="CoreLib\TableModule.cs" />
     <Compile Include="CoreLib\TableModule.cs" />

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

@@ -105,7 +105,8 @@ namespace MoonSharp.Interpreter.Tree.Expressions
 
 
 			m_Statement.Compile(bc);
 			m_Statement.Compile(bc);
 
 
-			bc.Emit_Ret(0);
+			if (bc.GetLastInstruction().OpCode != OpCode.Ret)
+				bc.Emit_Ret(0);
 
 
 			I.NumVal = bc.GetJumpPointForNextInstruction();
 			I.NumVal = bc.GetJumpPointForNextInstruction();
 
 

+ 24 - 4
src/MoonSharp.Interpreter/Tree/Expressions/IndexExpression.cs

@@ -26,15 +26,35 @@ namespace MoonSharp.Interpreter.Tree.Expressions
 		public override void Compile(ByteCode bc)
 		public override void Compile(ByteCode bc)
 		{
 		{
 			m_BaseExp.Compile(bc);
 			m_BaseExp.Compile(bc);
-			m_IndexExp.Compile(bc);
-			bc.Emit_LoadIdx();
+
+			if (m_IndexExp is LiteralExpression)
+			{
+				LiteralExpression lit = (LiteralExpression)m_IndexExp;
+				bc.Emit_Index(lit.Value);
+			}
+			else
+			{
+				m_IndexExp.Compile(bc);
+				bc.Emit_Index();
+			}
 		}
 		}
 
 
 		public void CompileAssignment(ByteCode bc, int stackofs, int tupleidx)
 		public void CompileAssignment(ByteCode bc, int stackofs, int tupleidx)
 		{
 		{
 			m_BaseExp.Compile(bc);
 			m_BaseExp.Compile(bc);
-			m_IndexExp.Compile(bc);
-			bc.Emit_StoreIdx(stackofs, tupleidx);
+
+			if (m_IndexExp is LiteralExpression)
+			{
+				LiteralExpression lit = (LiteralExpression)m_IndexExp;
+				bc.Emit_IndexSet(stackofs, tupleidx, lit.Value);
+			}
+			else
+			{
+				m_IndexExp.Compile(bc);
+				bc.Emit_IndexSet(stackofs, tupleidx);
+			}
+
+
 		}
 		}
 	}
 	}
 }
 }

+ 5 - 0
src/MoonSharp.Interpreter/Tree/Expressions/LiteralExpression.cs

@@ -13,6 +13,11 @@ namespace MoonSharp.Interpreter.Tree.Expressions
 	{
 	{
 		DynValue m_Value;
 		DynValue m_Value;
 
 
+		public DynValue Value
+		{
+			get { return m_Value; }
+		}
+
 		public LiteralExpression(IParseTree context, ScriptLoadingContext lcontext, DynValue rvalue)
 		public LiteralExpression(IParseTree context, ScriptLoadingContext lcontext, DynValue rvalue)
 			: base(context, lcontext)
 			: base(context, lcontext)
 		{
 		{

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

@@ -31,7 +31,7 @@ namespace MoonSharp.Interpreter.Tree
 			{
 			{
 				bc.Emit_Copy(0);
 				bc.Emit_Copy(0);
 				bc.Emit_Literal(DynValue.NewString(m_Name));
 				bc.Emit_Literal(DynValue.NewString(m_Name));
-				bc.Emit_LoadIdx();
+				bc.Emit_Index();
 				bc.Emit_Swap(0, 1);
 				bc.Emit_Swap(0, 1);
 				++argslen;
 				++argslen;
 			}
 			}

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

@@ -76,12 +76,11 @@ namespace MoonSharp.Interpreter.Tree.Statements
 			{
 			{
 				bc.Emit_Literal(DynValue.Nil);
 				bc.Emit_Literal(DynValue.Nil);
 				bc.Emit_Store(m_FuncSymbol, 0, 0);
 				bc.Emit_Store(m_FuncSymbol, 0, 0);
-				bc.Emit_Pop();
-				m_FuncDef.Compile(bc, () => SetFunction(bc), m_FriendlyName);
+				m_FuncDef.Compile(bc, () => SetFunction(bc, 2), m_FriendlyName);
 			}
 			}
 			else if (m_MethodName == null)
 			else if (m_MethodName == null)
 			{
 			{
-				m_FuncDef.Compile(bc, () => SetFunction(bc), m_FriendlyName);
+				m_FuncDef.Compile(bc, () => SetFunction(bc, 1), m_FriendlyName);
 			}
 			}
 			else
 			else
 			{
 			{
@@ -98,21 +97,21 @@ namespace MoonSharp.Interpreter.Tree.Statements
 			foreach (string str in m_TableAccessors)
 			foreach (string str in m_TableAccessors)
 			{
 			{
 				bc.Emit_Literal(DynValue.NewString(str));
 				bc.Emit_Literal(DynValue.NewString(str));
-				bc.Emit_LoadIdx();
+				bc.Emit_Index();
 				cnt += 2;
 				cnt += 2;
 			}
 			}
 
 
 			bc.Emit_Literal(DynValue.NewString(m_MethodName));
 			bc.Emit_Literal(DynValue.NewString(m_MethodName));
 
 
-			bc.Emit_StoreIdx(0, 0);
+			bc.Emit_IndexSet(0, 0);
 
 
 			return 2 + cnt;
 			return 2 + cnt;
 		}
 		}
 
 
-		private int SetFunction(Execution.VM.ByteCode bc)
+		private int SetFunction(Execution.VM.ByteCode bc, int numPop)
 		{
 		{
 			int num = bc.Emit_Store(m_FuncSymbol, 0, 0);
 			int num = bc.Emit_Store(m_FuncSymbol, 0, 0);
-			bc.Emit_Pop();
+			bc.Emit_Pop(numPop);
 			return num + 1;
 			return num + 1;
 		}
 		}
 
 

+ 45 - 2
src/MoonSharp/Program.cs

@@ -51,8 +51,51 @@ namespace MoonSharp
 			}
 			}
 			else
 			else
 			{
 			{
-				Console.WriteLine("Sorry, at the moment, only file operations are supported:");
-				Console.WriteLine("\tUsage : MoonSharp [filename]");
+				Console.WriteLine("Type <enter> twice to execute code.\n");
+
+				Script script = new Script();
+
+				script.Globals["print"] = DynValue.NewCallback(new CallbackFunction(Print));
+
+				string cmd = "";
+
+				while (true)
+				{
+					Console.Write("{0}> ", string.IsNullOrEmpty(cmd) ? "" : ">");
+					string s = Console.ReadLine();
+
+					if (s != "")
+					{
+						cmd += s + "\n";
+						continue;
+					}
+
+					if (cmd.Length == 0)
+						continue;
+
+					Console.WriteLine("=====");
+					Console.WriteLine("{0}", cmd);
+					Console.WriteLine("=====");
+
+					if (cmd == "exit")
+						return;
+
+					try
+					{
+						Console.WriteLine("={0}", script.DoString(cmd));
+					}
+					catch (Exception ex)
+					{
+						Console.WriteLine("Error: {0}", ex.Message);
+					}
+
+					cmd = "";
+
+				}
+
+
+
+
 			}
 			}
 		}
 		}
 
 

+ 10 - 9
src/PerformanceComparison/Program.cs

@@ -16,12 +16,12 @@ namespace PerformanceComparison
 	class Program
 	class Program
 	{
 	{
 #if PROFILER
 #if PROFILER
-		const int ITERATIONS = 1000;
+		const int ITERATIONS = 10;
 #else
 #else
-		const int ITERATIONS = 1;
+		const int ITERATIONS = 100;
 #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 = {}
@@ -71,15 +71,15 @@ if Find_Solution( 1 ) then
     for i = 1, N do
     for i = 1, N do
  	for j = 1, N do
  	for j = 1, N do
   	    if board[i][j] then 
   	    if board[i][j] then 
-		print( 'Q' )
+		--print( 'Q' )
 	    else 
 	    else 
-		print( 'x' )
+		--print( 'x' )
 	    end
 	    end
 	end
 	end
-	print( '|' )
+	--print( '|' )
     end
     end
 else
 else
-    print( 'NO!' )
+    --print( 'NO!' )
 end
 end
  
  
 			";
 			";
@@ -125,7 +125,8 @@ end
 
 
 			sw = Stopwatch.StartNew();
 			sw = Stopwatch.StartNew();
 
 
-			Script.RunString("return 0;");
+			var _s = new Script();
+			_s.LoadString(scriptText);
 
 
 			sw.Stop();
 			sw.Stop();
 
 

+ 1 - 0
src/moonsharp.sln

@@ -32,6 +32,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}.Debug|x86.ActiveCfg = Debug|x86
 		{2A4BD262-D6EB-4611-A28B-27B6DAEB089B}.Debug|x86.ActiveCfg = Debug|x86
 		{2A4BD262-D6EB-4611-A28B-27B6DAEB089B}.Debug|x86.Build.0 = Debug|x86
 		{2A4BD262-D6EB-4611-A28B-27B6DAEB089B}.Debug|x86.Build.0 = Debug|x86
 		{2A4BD262-D6EB-4611-A28B-27B6DAEB089B}.Release|Any CPU.ActiveCfg = Release|Any CPU
 		{2A4BD262-D6EB-4611-A28B-27B6DAEB089B}.Release|Any CPU.ActiveCfg = Release|Any CPU