Skip to content

Commit

Permalink
Add io.write_to_file() helper. Relates to lord-server#925. Needs for
Browse files Browse the repository at this point in the history
  • Loading branch information
alek13 committed Jul 2, 2024
1 parent 22e17b0 commit c89f6c2
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
2 changes: 1 addition & 1 deletion .luacheckrc
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ read_globals = {

io = { fields = {
-- our Core/helpers:
"file_exists",
"file_exists", "write_to_file"
} },

os = { fields = {
Expand Down
31 changes: 31 additions & 0 deletions mods/lord/Core/helpers/src/lua_ext/io.lua
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit c89f6c2

Please sign in to comment.