Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- local lsave = {} -- will carry the public functions; loadfile does not like globals :/
- function lsave.load(sFile) -- This function will check that lsave saved the file in the future.
- if not fs.exists(sFile) then return false, "nofile" end -- We can't load a file that doesn't exist.
- local hHandle = io.open(sFile, "r")
- local err, res = pcall(function() return setfenv(loadfile(sFile),getfenv())() end)
- if not err then
- return false, res
- end
- return true, res
- end
- -- Saving helper format strings/functions
- lsave.types = {}
- lsave.types.boolean = "data[%q] = %s"
- lsave.types.string = "data[%q] = %q"
- lsave.types.number = "data[%q] = %d"
- -- Saving function
- function lsave.save(sFile, data)
- if type(sFile) ~= "string" or type(data) ~= "table" then
- return false, "Invalid arguments"
- end
- local sData = "local data = {} -- This file, generated by lsave 0.5. Edit at your own risk.\n\n"
- for k, v in pairs(data) do
- local sDataType = type(v)
- local saveHelper = lsave.types[sDataType]
- if not saveHelper then
- -- We have problem, let's just print it, and continue without saving it.
- print("Warning: (saveToFile) unknown data type (ignoring), in key: " .. k)
- else
- -- No errors, save it.
- if type(saveHelper) == "string" then
- sData = sData .. string.format(saveHelper, k, tostring(v)) .. "\n"
- elseif type(saveHelper) == "function" then -- For the future, and custom stuff.
- sData = sData .. saveHelper(k, v) .. "\n"
- end
- end
- end
- sData = sData .. "\nreturn data" -- We need to return the config in order to retrieve it.
- -- Delete and save.
- local hHandle, err = io.open(sFile, "w")
- if not hHandle then
- return false, err
- end
- hHandle:write(sData)
- hHandle:close()
- return true
- end
- return lsave -- This, so you can do "lsave = loadfile("lsave")()"
- -- Remove the line if you want to just paste it in your program, instead.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement