Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- json = require("/json")
- function createDatabase(dbName)
- if not io.open(dbName, "r") then
- db = io.open(dbName, "w")
- io.close(db)
- end
- end
- function jsonFileToTable(fileName)
- aTable = {}
- jsonFile = io.open(fileName, "r")
- jsonString = jsonFile:read("*all")
- if jsonString:len() > 0 then
- aTable = json.decode(jsonString)
- end
- io.close(jsonFile)
- return aTable
- end
- function tableToJSONFile(dbTable, fileName)
- jsonString = json.encode(dbTable)
- jsonFile = io.open(fileName, "w")
- io.output(jsonFile)
- io.write(jsonString)
- io.close(jsonFile)
- end
- -- yoinked from user Michal Kottman on stackoverflow, iterator to sort a table
- function spairs(t)
- -- collect the keys
- local keys = {}
- for k in pairs(t) do keys[#keys+1] = k end
- -- sort the keys
- table.sort(keys)
- -- return the iterator function
- local i = 0
- return function()
- i = i + 1
- if keys[i] then
- return keys[i], t[keys[i]]
- end
- end
- end
- function printDatabase(db)
- for k, v in spairs(db) do
- print(k..":")
- for x, y in ipairs(v) do
- print(" "..y["Level"]..": "..y["Amount"])
- end
- print("")
- end
- end
- function stripLevel(enchantName)
- s = enchantName:find("%sI") or enchantName:find("%sV")
- if s then
- enchantName = enchantName:sub(0, s-1)
- end
- return enchantName
- end
- function insertEnchant(db, enchant)
- noLevel = stripLevel(enchant)
- if db[noLevel] then
- for k, v in ipairs(db[noLevel]) do
- if v["Level"] == enchant then
- v["Amount"] = v["Amount"] + 1
- return
- end
- end
- table.insert(db[noLevel], {Level = enchant, Amount = 1})
- else
- db[noLevel] = {{Level = enchant, Amount = 1}}
- end
- end
- function removeEnchant(db, enchantLevel)
- noLevel = stripLevel(enchantLevel)
- if db[noLevel] then
- for k, v in ipairs(db[noLevel]) do
- if v["Level"] == enchantLevel then
- if v["Amount"] > 0 then
- v["Amount"] = v["Amount"] - 1
- else
- print("No "..enchantLevel.." books remaining.")
- end
- return
- end
- end
- end
- end
- createDatabase("database.json")
- local database = jsonFileToTable("database.json")
- insertEnchant(database, "Sharpness V")
- insertEnchant(database, "Sharpness V")
- insertEnchant(database, "Soul Stealer III")
- removeEnchant(database, "Sharpness V")
- insertEnchant(database, "Sharpness IV")
- insertEnchant(database, "Sharpness I")
- insertEnchant(database, "Sharpness III")
- insertEnchant(database, "Efficiency IV")
- insertEnchant(database, "Silk Touch")
- removeEnchant(database, "LOL III")
- tableToJSONFile(database, "database.json")
- local database = jsonFileToTable("database.json")
- printDatabase(database)
Add Comment
Please, Sign In to add comment