druidbruce

AEst/stockpile settingsPersistence

Apr 25th, 2016
211
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.72 KB | None | 0 0
  1. os.loadAPI("tablePersistence")
  2.  
  3. settings = nil
  4. local SETTINGS_FILE = "stockpile/stockpile.json"
  5.  
  6. function load()
  7. local loaded = tablePersistence.load(SETTINGS_FILE)
  8.  
  9. if loaded == nil then
  10. loaded = { stockedItems = {} }
  11. end
  12.  
  13. settings = loaded
  14. end
  15.  
  16. function save()
  17. tablePersistence.save(SETTINGS_FILE, settings)
  18. end
  19.  
  20. function getStockedItems()
  21. if settings == nil then
  22. print("settings is nil")
  23. end
  24. return settings.stockedItems
  25. end
  26.  
  27. function removeStockedItem(item)
  28. settings.stockedItems[itemKey(item)] = nil
  29. save()
  30. end
  31.  
  32. function setItemThreshold(item, threshold)
  33. local currentSettings = itemSettings(item)
  34. if currentSettings == nil then
  35. settings.stockedItems[itemKey(item)] = {
  36. item = item,
  37. threshold = threshold
  38. }
  39. else
  40. currentSettings.threshold = threshold
  41. end
  42.  
  43. save()
  44. end
  45.  
  46. function getItemThreshold(item)
  47. local item = itemSettings(item)
  48.  
  49. if item ~= nil then
  50. return item.threshold
  51. else
  52. return nil
  53. end
  54. end
  55.  
  56. function itemIsStocked(item)
  57. return itemSettings(item) ~= nil
  58. end
  59.  
  60. function itemSettings(item)
  61. return getSettings().stockedItems[itemKey(item)]
  62. end
  63.  
  64. function itemFromKey(key)
  65. local parts = split(key, "/")
  66. return { id = parts[1], dmg = parts[2] }
  67. end
  68.  
  69. function itemKey(item)
  70. local key = item.id .. "/" .. item.dmg
  71.  
  72. if item.nbt_hash ~= nil then
  73. key = key .. "/" .. item.nbt_hash
  74. end
  75.  
  76. return key
  77. end
  78.  
  79. function split(str, sep)
  80. local result = {}
  81. local regex = ("([^%s]+)"):format(sep)
  82. for each in str:gmatch(regex) do
  83. table.insert(result, each)
  84. end
  85. return result
  86. end
  87.  
  88. function getSettings()
  89. if settings == nil then
  90. load()
  91. end
  92. return settings
  93. end
Add Comment
Please, Sign In to add comment