commit bc3198be70054f229808aecda18ebcb5ad96456b Author: Rivulet Date: Sat Apr 4 23:47:18 2026 +0000 Add localdb.lua diff --git a/localdb.lua b/localdb.lua new file mode 100644 index 0000000..7c48a5d --- /dev/null +++ b/localdb.lua @@ -0,0 +1,86 @@ +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 \ No newline at end of file