added disk driver

This commit is contained in:
2025-12-12 13:28:21 -05:00
parent caa0d1471d
commit ed2c0049e4
2 changed files with 96 additions and 0 deletions

90
disk-driver.lua Normal file
View File

@@ -0,0 +1,90 @@
local diskDrive = peripheral.find("drive")
local monitor = require("monitor-driver")
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()
monitor.writeLine("Initializing Data Storage...")
if diskDrive and diskDrive.isDiskPresent() then
monitor.writeLine("Disk detected. Initializing data storage.")
local path = getFilePath()
if path and not fs.exists(path) then
saveData({})
end
return true
end
return false
end
return { getValue = getValue, updateValue = updateValue, writeValue = writeValue, initialize = initialize }