remie92

salt

Aug 4th, 2025
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.71 KB | None | 0 0
  1. --[[ Save and Load Tables (SALT) ]]--
  2. --
  3. --Url: http://github.com/VaiN474/salt.git
  4. --
  5. --Author: VaiN474 - http://github.com/VaiN474
  6. --Last Update: Aug 15, 2017
  7. --Description: Recursively saves table data to a file, human-readable and
  8. -- indented. Tables are loaded using loadfile().
  9. -- Supported types: number, string, boolean, sub-tables of same.
  10. --
  11. --License: MIT (read LICENSE for more details)
  12. --
  13. --Example Usage:
  14. --
  15. --salt = require("salt")
  16. --salt.save(my_table,"/path/to/file")
  17. --
  18. --my_table,err = salt.load("/path/to/file")
  19. --
  20.  
  21. local salt = {}
  22.  
  23. -- compressed is optional, if true it will not include unneccesary spaces, indentation, or line endings
  24. function salt.save(tbl,file,compressed)
  25.  
  26. local f,err = io.open(file,"w")
  27. if err then print(err) return end
  28. local indent = 1
  29.  
  30. -- local functions to make things easier
  31. local function exportstring(s)
  32. s=string.format("%q",s)
  33. s=s:gsub("\\\n","\\n")
  34. s=s:gsub("\r","")
  35. s=s:gsub(string.char(26),"\"..string.char(26)..\"")
  36. return s
  37. end
  38. local function serialize(o)
  39. if type(o) == "number" then
  40. f:write(o)
  41. elseif type(o) == "boolean" then
  42. if o then f:write("true") else f:write("false") end
  43. elseif type(o) == "string" then
  44. f:write(exportstring(o))
  45. elseif type(o) == "table" then
  46. f:write("{" .. (compressed and "" or "\n"))
  47. indent = indent + 1
  48. local tab = ""
  49. for i=1,indent do tab = tab .. " " end
  50. for k,v in pairs(o) do
  51. f:write((compressed and "" or tab) .. "[")
  52. serialize(k)
  53. f:write("]" .. (compressed and "=" or " = "))
  54. serialize(v)
  55. f:write("," .. (compressed and "" or "\n"))
  56. end
  57. indent = indent - 1
  58. tab = ""
  59. for i=1,indent do tab = tab .. " " end
  60. f:write((compressed and "" or tab) .. "}")
  61. else
  62. print("unable to serialzie data: "..tostring(o))
  63. f:write("nil," .. (compressed and "" or " -- ***ERROR: unsupported data type: "..type(o).."!***"))
  64. end
  65. end
  66.  
  67. f:write("return {" .. (compressed and "" or "\n"))
  68. local tab = " "
  69. for k,v in pairs(tbl) do
  70. f:write((compressed and "" or tab) .. "[")
  71. serialize(k)
  72. f:write("]" .. (compressed and "=" or " = "))
  73. serialize(v)
  74. f:write("," .. (compressed and "" or "\n"))
  75. end
  76. f:write("}")
  77. f:close()
  78. end
  79.  
  80. function salt.load(file)
  81. local data,err = loadfile(file)
  82. if err then return nil,err else return data() end
  83. end
  84.  
  85. return salt
Add Comment
Please, Sign In to add comment