Browse Source

Update: support file:read(number)

AnnulusGames 1 year ago
parent
commit
22b588a56a
2 changed files with 20 additions and 1 deletions
  1. 5 0
      src/Lua/Standard/IO/FileHandle.cs
  2. 15 1
      src/Lua/Standard/IO/IOHelper.cs

+ 5 - 0
src/Lua/Standard/IO/FileHandle.cs

@@ -59,6 +59,11 @@ public class FileHandle : LuaUserData
         return reader!.ReadToEnd();
     }
 
+    public int ReadByte()
+    {
+        return stream.ReadByte();
+    }
+
     public void Write(ReadOnlySpan<byte> buffer)
     {
         stream.Write(buffer);

+ 15 - 1
src/Lua/Standard/IO/IOHelper.cs

@@ -92,8 +92,22 @@ internal static class IOHelper
                         throw new LuaRuntimeException(context.State.GetTraceback(), $"bad argument #{i + 1} to 'read' (number has no integer representation)");
                     }
 
-                    // TODO:
+                    var count = (int)d;
+                    using var byteBuffer = new PooledArray<byte>(count);
 
+                    for (int j = 0; j < count; j++)
+                    {
+                        var b = file.ReadByte();
+                        if (b == -1)
+                        {
+                            buffer.Span[0] = LuaValue.Nil;
+                            return 1;
+                        }
+
+                        byteBuffer[j] = (byte)b;
+                    }
+
+                    buffer.Span[i] = Encoding.UTF8.GetString(byteBuffer.AsSpan());
                 }
                 else
                 {