Browse Source

Merge branch 'implement-lua-error' of https://github.com/ixjf/moonsharp into pr/ixjf-set

Xanathar 6 years ago
parent
commit
22e0f742d7
1 changed files with 28 additions and 1 deletions
  1. 28 1
      src/MoonSharp.Interpreter/CoreLib/BasicModule.cs

+ 28 - 1
src/MoonSharp.Interpreter/CoreLib/BasicModule.cs

@@ -5,6 +5,7 @@ using System;
 using System.Collections.Generic;
 using System.Collections.Generic;
 using System.Globalization;
 using System.Globalization;
 using System.Text;
 using System.Text;
+using MoonSharp.Interpreter.Debugging;
 
 
 namespace MoonSharp.Interpreter.CoreLib
 namespace MoonSharp.Interpreter.CoreLib
 {
 {
@@ -84,7 +85,33 @@ namespace MoonSharp.Interpreter.CoreLib
 		public static DynValue error(ScriptExecutionContext executionContext, CallbackArguments args)
 		public static DynValue error(ScriptExecutionContext executionContext, CallbackArguments args)
 		{
 		{
 			DynValue message = args.AsType(0, "error", DataType.String, false);
 			DynValue message = args.AsType(0, "error", DataType.String, false);
-			throw new ScriptRuntimeException(message.String); // { DoNotDecorateMessage = true };
+            		DynValue level = args.AsType(1, "error", DataType.Number, true);
+
+            		Coroutine cor = executionContext.GetCallingCoroutine();
+
+            		WatchItem[] stacktrace = cor.GetStackTrace(0, executionContext.CallingLocation);
+
+            		var e = new ScriptRuntimeException(message.String);
+
+            		if (level.IsNil())
+            		{
+                		level = DynValue.NewNumber(1); // Default
+            		}
+
+            		if (level.Number > 0 && level.Number < stacktrace.Length)
+            		{
+                    		// Lua allows levels up to max. value of a double, while this has to be cast to int
+                    		// Probably never will be a problem, just leaving this note here
+                    		WatchItem wi = stacktrace[(int)level.Number];
+
+                    		e.DecorateMessage(executionContext.GetScript(), wi.Location);
+            		}
+            		else
+            		{
+                		e.DoNotDecorateMessage = true;
+            		}
+
+            		throw e;
 		}
 		}