Files
nova-corp/disk-driver.lua
2026-05-05 17:41:22 -04:00

102 lines
2.5 KiB
Lua

local diskDrive = peripheral.find("drive")
local function getFilePath()
if diskDrive and diskDrive.isDiskPresent() then
local path = diskDrive.getMountPath()
if path then
return fs.combine(path, "data.tbl")
end
end
return nil
end
local function loadData()
local path = getFilePath()
if path and fs.exists(path) then
local file = fs.open(path, "r")
local content = file.readAll()
file.close()
local parsed
if content then
parsed = textutils.unserialize(content)
end
return parsed or {}
end
return {}
end
local function saveData(data)
local path = getFilePath()
if path then
local file = fs.open(path, "w")
file.write(textutils.serialize(data))
file.close()
return true
end
return false
end
local function generateGuid()
local template ='xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'
return string.gsub(template, '[xy]', function (c)
local v = (c == 'x') and math.random(0, 0xf) or math.random(8, 0xb)
return string.format('%x', v)
end)
end
local function getValue(key)
local data = loadData()
for _, item in ipairs(data) do
if item.Key == key then
return item.Value
end
end
return nil
end
local function updateValue(key, value)
local data = loadData()
for _, item in ipairs(data) do
if item.Key == key then
item.Value = value
saveData(data)
return true
end
end
return false
end
local function writeValue(key, value)
local data = loadData()
local guid = generateGuid()
table.insert(data, { GeneratedGuid = guid, Key = key, Value = value })
saveData(data)
return guid
end
local function initialize()
local monitor = peripheral.find("monitor")
if monitor then monitor.write("Initializing Data Storage...") end
if diskDrive and diskDrive.isDiskPresent() then
if monitor then monitor.write("Disk detected. Initializing data storage.") end
local path = getFilePath()
if path and not fs.exists(path) then
saveData({})
end
return true
end
return false
end
local function getRead(key)
local value = getValue(key)
if value then
return value
end
print("Enter value for " .. key .. ":")
local input = read()
writeValue(key, input)
return input
end
return { getValue = getValue, updateValue = updateValue, writeValue = writeValue, initialize = initialize, getRead = getRead }