Browse Source

Fix: Implicit conversion from string to number, which is out of specification

Akeit0 1 year ago
parent
commit
0968ff6e11
3 changed files with 16 additions and 4 deletions
  1. 1 1
      src/Lua/LuaTable.cs
  2. 13 1
      src/Lua/LuaValue.cs
  3. 2 2
      src/Lua/Runtime/LuaVirtualMachine.cs

+ 1 - 1
src/Lua/LuaTable.cs

@@ -267,7 +267,7 @@ public sealed class LuaTable
     [MethodImpl(MethodImplOptions.AggressiveInlining)]
     static bool TryGetInteger(LuaValue value, out int integer)
     {
-        if (value.TryRead<double>(out var num) && MathEx.IsInteger(num))
+        if (value.TryReadNumber(out var num) && MathEx.IsInteger(num))
         {
             integer = (int)num;
             return true;

+ 13 - 1
src/Lua/LuaValue.cs

@@ -203,7 +203,19 @@ public readonly struct LuaValue : IEquatable<LuaValue>
         result = default!;
         return false;
     }
-
+    
+    [MethodImpl(MethodImplOptions.AggressiveInlining)]
+    internal bool TryReadNumber(out double result)
+    {
+        if (type == LuaValueType.Number)
+        {
+            result = value;
+            return true;
+        }
+        result = default!;
+        return false;
+    }
+   
     public T Read<T>()
     {
         if (!TryRead<T>(out var result)) throw new InvalidOperationException($"Cannot convert LuaValueType.{Type} to {typeof(T).FullName}.");

+ 2 - 2
src/Lua/Runtime/LuaVirtualMachine.cs

@@ -581,7 +581,7 @@ public static partial class LuaVirtualMachine
                             {
                                 compareResult = StringComparer.Ordinal.Compare(strB, strC) < 0;
                             }
-                            else if (vb.TryRead<double>(out var valueB) && vc.TryRead<double>(out var valueC))
+                            else if (vb.TryReadNumber(out var valueB) && vc.TryReadNumber(out var valueC))
                             {
                                 compareResult = valueB < valueC;
                             }
@@ -629,7 +629,7 @@ public static partial class LuaVirtualMachine
                             {
                                 compareResult = StringComparer.Ordinal.Compare(strB, strC) <= 0;
                             }
-                            else if (vb.TryRead<double>(out var valueB) && vc.TryRead<double>(out var valueC))
+                            else if (vb.TryReadNumber(out var valueB) && vc.TryReadNumber(out var valueC))
                             {
                                 compareResult = valueB <= valueC;
                             }