86 lines
1.9 KiB
Lua
86 lines
1.9 KiB
Lua
local db = {}
|
|
local file = fs.open("data.db","r+")
|
|
if not file then error("failed to open db file") end
|
|
|
|
local function readTable()
|
|
file.seek("set")
|
|
return textutils.unserialise(file.readAll() or "{}") or {}
|
|
end
|
|
|
|
local function writeTable(t)
|
|
file.seek("set")
|
|
file.write(textutils.serialise(t))
|
|
file.flush()
|
|
end
|
|
|
|
---returns a list of all materials
|
|
---@return string[]
|
|
function db.getMaterials()
|
|
local table = readTable()
|
|
local materials = {}
|
|
for k,_ in pairs(table.materials or {}) do
|
|
materials[#materials+1] = k
|
|
end
|
|
return materials
|
|
end
|
|
|
|
---gets the price of a material
|
|
---@param mat string
|
|
---@return number
|
|
function db.getPrice(mat)
|
|
return (readTable().materials or {})[mat]
|
|
end
|
|
|
|
---returns a list of all currencies
|
|
---@return string[]
|
|
function db.getCurrencies()
|
|
local table = readTable()
|
|
local currencies = {}
|
|
for k,_ in pairs(table.currencies or {}) do
|
|
currencies[#currencies+1] = k
|
|
end
|
|
return currencies
|
|
end
|
|
|
|
---gets the worth of a currency
|
|
---@param cur string
|
|
---@return number
|
|
function db.getCurrencyWorth(cur)
|
|
return (readTable().currencies or {})[cur]
|
|
end
|
|
|
|
---sets the price of a material
|
|
---@param mat string
|
|
---@param price number
|
|
function db.setPrice(mat,price)
|
|
local table = readTable()
|
|
if not table.materials then table.materials = {} end
|
|
table.materials[mat] = price
|
|
writeTable(table)
|
|
end
|
|
|
|
---sets the worth of a currency
|
|
---@param cur string
|
|
---@param worth number
|
|
function db.setWorth(cur,worth)
|
|
local table = readTable()
|
|
if not table.currencies then table.currencies = {} end
|
|
table.currencies[cur] = worth
|
|
writeTable(table)
|
|
end
|
|
|
|
---gets the currency unit string
|
|
---@return string
|
|
function db.getCurrencyUnit()
|
|
return readTable().currency_unit or "cr"
|
|
end
|
|
|
|
---sets the currency unit string
|
|
---@param unit string
|
|
function db.setCurrencyUnit(unit)
|
|
local table = readTable()
|
|
table.currency_unit = unit
|
|
writeTable(table)
|
|
end
|
|
|
|
return db |