From c89f6c274092f47fbdfd4f73793f13fc583e519d Mon Sep 17 00:00:00 2001 From: alek13 Date: Tue, 2 Jul 2024 19:23:43 +0300 Subject: [PATCH] Add `io.write_to_file()` helper. Relates to #925. Needs for #1502 --- .luacheckrc | 2 +- mods/lord/Core/helpers/src/lua_ext/io.lua | 31 +++++++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/.luacheckrc b/.luacheckrc index 440c6cf8e..fcf013e75 100644 --- a/.luacheckrc +++ b/.luacheckrc @@ -42,7 +42,7 @@ read_globals = { io = { fields = { -- our Core/helpers: - "file_exists", + "file_exists", "write_to_file" } }, os = { fields = { diff --git a/mods/lord/Core/helpers/src/lua_ext/io.lua b/mods/lord/Core/helpers/src/lua_ext/io.lua index 7868ad124..6330002f1 100644 --- a/mods/lord/Core/helpers/src/lua_ext/io.lua +++ b/mods/lord/Core/helpers/src/lua_ext/io.lua @@ -10,3 +10,34 @@ function io.file_exists(name) return false end + +--- Writes `content` into file by path `filepath` +--- Returns `true` if success or `false, error_code, error_message` +--- +--- @param filepath string +--- @param content string +--- @param mode string default: `"w"` +--- +--- @return file|nil,nil|number,nil|string +--- +--- @overload fun(filepath:string, content:string):boolean,nil|number,nil|string +--- @overload fun(filepath:string, content:string):boolean,nil|number,nil|string +function io.write_to_file(filepath, content, mode) + mode = mode or "w" + + local file, error_message, error_code = io.open(filepath, mode) + if not file then + return false, error_code, error_message + end + + local success + success, error_message, error_code = file:write(content) + if not success then + file:close() + return false, (error_code or -1), (error_message or "unknown reason") + end + + file:close() + + return true +end