Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- local function save(filename, data)
- local handle, err = fs.open(filename, 'w') -- w for write
- if handle then
- handle.write(textutils.serialize(data)) -- write the data, serialized.
- handle.close() -- closing the handle is what actually saves.
- -- very important to close filehandles.
- else
- -- Throw an error pointing to the calling function.
- error("Failed to save data: " .. tostring(err), 2)
- end
- end
- local function load(filename, default_value)
- local handle = fs.open(filename, 'r') -- r for read
- if handle then
- local data = handle.readAll()
- handle.close() -- again, important to close these.
- return textutils.unserialize(data) -- Unserialize the data and return it.
- end
- -- If we got here, the file did not exist.
- return default_value
- end
- -- Usage
- local data = {x = 32, y = 64}
- save("position.txt", data)
- local loaded_data = load("position.txt", {x = 0, y = 0})
- -- loaded_data will be {x = 32, y = 64}
- -- Unless you delete `position.txt`, in which case it will be {x = 0, y = 0}
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement