Browse Source

Fix: Closure GetUpValueFromDescription

Akeit0 1 year ago
parent
commit
28f7691221
1 changed files with 12 additions and 10 deletions
  1. 12 10
      src/Lua/Runtime/Closure.cs

+ 12 - 10
src/Lua/Runtime/Closure.cs

@@ -17,7 +17,7 @@ public sealed class Closure : LuaFunction
         for (int i = 0; i < proto.UpValues.Length; i++)
         {
             var description = proto.UpValues[i];
-            var upValue = GetUpValueFromDescription(state, environment == null ? state.EnvUpValue : UpValue.Closed(environment), proto, description, 1);
+            var upValue = GetUpValueFromDescription(state, state.CurrentThread, environment == null ? state.EnvUpValue : UpValue.Closed(environment), description);
             upValues.Add(upValue);
         }
 
@@ -39,23 +39,25 @@ public sealed class Closure : LuaFunction
         upValues[index].SetValue(value);
     }
 
-
-    static UpValue GetUpValueFromDescription(LuaState state, UpValue envUpValue, Chunk proto, UpValueInfo description, int depth)
+    static UpValue GetUpValueFromDescription(LuaState state, LuaThread thread, UpValue envUpValue, UpValueInfo description)
     {
         if (description.IsInRegister)
         {
-            var thread = state.CurrentThread;
-            var callStack = thread.GetCallStackFrames();
-            var frame = callStack[^depth];
-            return state.GetOrAddUpValue(thread, frame.Base + description.Index);
+            return state.GetOrAddUpValue(thread, thread.GetCallStackFrames()[^1].Base + description.Index);
         }
-        else if (description.Index == -1) // -1 is global environment
+
+        if (description.Index == -1) // -1 is global environment
         {
             return envUpValue;
         }
-        else
+
         {
-            return GetUpValueFromDescription(state, envUpValue, proto.Parent!, proto.Parent!.UpValues[description.Index], depth + 1);
+            if (thread.GetCallStackFrames()[^1].Function is Closure parentClosure)
+            {
+                return parentClosure.UpValues[description.Index];
+            }
+
+            throw new InvalidOperationException("invalid upvalue description.");
         }
     }
 }