Created
October 20, 2021 07:51
-
-
Save meta-hub/424263e3d9b44e7fc1bc21c3d9c26ef3 to your computer and use it in GitHub Desktop.
File/IO helper with Lua
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
local fileMt = {} | |
fileMt.__index = fileMt | |
function fileMt:exists() | |
local f = io.open(self.path,"r") | |
if f then | |
f:close() | |
end | |
return (f ~= nil) | |
end | |
function fileMt:read(concat) | |
if not self:exists() then | |
return error("file does not exist",2) | |
end | |
local f = io.open(self.path,"r") | |
local lines = {} | |
for line in f:lines() do | |
table.insert(lines,line) | |
end | |
f:close() | |
return (concat and table.concat(lines,"\n") or lines) | |
end | |
function fileMt:write(content) | |
if not content then | |
return error("content not provided",2) | |
end | |
content = tostring(content) | |
local f = io.open(self.path,"a+") | |
if not f then | |
return error("error writing to file",1) | |
end | |
f:write(content) | |
f:close() | |
end | |
function fileMt:overwrite(content) | |
if not content then | |
return error("content not provided",2) | |
end | |
content = tostring(content) | |
local f = io.open(self.path,"w+") | |
if not f then | |
return error("error writing to file",1) | |
end | |
f:write(content) | |
f:close() | |
end | |
file = {} | |
setmetatable(file,{ | |
__call = function(self,path) | |
if type(path) ~= "string" then | |
return error("path not provided",2) | |
end | |
return setmetatable({path = path},fileMt) | |
end | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment