1
0
mirror of https://github.com/SquidDev-CC/CC-Tweaked synced 2025-01-09 08:50:29 +00:00

Add r+/w+ support to io library

This commit is contained in:
Jonathan Coates 2024-05-26 10:16:33 +01:00
parent 4d619de357
commit d48b85d50c
No known key found for this signature in database
GPG Key ID: B9E431FF07C98D06
3 changed files with 28 additions and 11 deletions

View File

@ -309,10 +309,10 @@ public class FSAPI implements ILuaAPI {
* <p>
* The {@code mode} string can be any of the following:
* <ul>
* <li><strong>"r"</strong>: Read mode</li>
* <li><strong>"w"</strong>: Write mode</li>
* <li><strong>"a"</strong>: Append mode</li>
* <li><strong>"r+"</strong>: Update mode (allows reading and writing), all data is preserved</li>
* <li><strong>"r"</strong>: Read mode.</li>
* <li><strong>"w"</strong>: Write mode.</li>
* <li><strong>"a"</strong>: Append mode.</li>
* <li><strong>"r+"</strong>: Update mode (allows reading and writing), all data is preserved.</li>
* <li><strong>"w+"</strong>: Update mode, all data is erased.</li>
* </ul>
* <p>

View File

@ -365,24 +365,26 @@ end
-- or [`nil`], plus an error message.
--
-- The `mode` string can be any of the following:
-- - **"r"**: Read mode
-- - **"w"**: Write mode
-- - **"a"**: Append mode
-- - **"r"**: Read mode.
-- - **"w"**: Write mode.
-- - **"a"**: Append mode.
-- - **"r+"**: Update mode (allows reading and writing), all data is preserved.
-- - **"w+"**: Update mode, all data is erased.
--
-- The mode may also have a `b` at the end, which opens the file in "binary
-- mode". This allows you to read binary files, as well as seek within a file.
-- mode". This has no impact on functionality.
--
-- @tparam string filename The name of the file to open.
-- @tparam[opt] string mode The mode to open the file with. This defaults to `rb`.
-- @tparam[opt] string mode The mode to open the file with. This defaults to `r`.
-- @treturn[1] Handle The opened file.
-- @treturn[2] nil In case of an error.
-- @treturn[2] string The reason the file could not be opened.
-- @changed 1.111.0 Add support for `r+` and `w+`.
function open(filename, mode)
expect(1, filename, "string")
expect(2, mode, "string", "nil")
local sMode = mode and mode:gsub("%+", "") or "r"
local file, err = fs.open(filename, sMode)
local file, err = fs.open(filename, mode or "r")
if not file then return nil, err end
return make_file(file)

View File

@ -329,4 +329,19 @@ describe("The io library", function()
expect(read_all(file)):eq("alo\n " .. t .. " ;end of file\n")
end)
end)
describe("read/write handles", function()
it("can read and write to a file", function()
write_file(file, "an example file")
local handle = io.open(file, "r+")
expect(handle:read(3)):eq("an ")
handle:write("exciting file")
expect(handle:seek("cur")):eq(16)
handle:seek("set", 0)
expect(handle:read("*a")):eq("an exciting file")
end)
end)
end)