Thought maybe someone would actually find it useful.
You can save this as an api but then it'll be apiName.files, up to you how you load the code. I would use dofile or something.
Anyway, here you go.
local ft_mt = {}
ft_mt.__index = function(t,k)
local name = tostring(k)
if not fs.exists(name) then return nil end
local handle = fs.open(name, "r")
if not handle then return nil end
local content = handle.readAll()
handle.close()
return content
end
ft_mt.__newindex = function(t,k,v)
local name = tostring(k)
local handle = fs.open(name, "w")
if not handle then return end
handle.write(tostring(v))
handle.close()
end
files = {}
setmetatable(files, ft_mt)
Basically lets you edit files using files["filename/or/path/here"]
So you can read the file using it's path as they key, or you can set the files content using
the key too.
For example, you might want to keep track of where the turtle is, so maybe you name the files table, database.
Then you can go, database.position = textutils.serialize({5,3,2})
Then you can get your position back!
position = textutils.unserialize(database.position)
It's beautiful right! Easy persistence, You can create as many keys as you like, and you know they'll be there on restart.. I see so much potential for mining programs!
I might eventually modify this to store the type information with the file and provide file stored tables. So you can use a table per usual as if it wasn't anything special.
table.number = 5
– Restart computer –
print(table.number).. prints 5!