iteration
This commit is contained in:
79
lib/lns.lua
Normal file
79
lib/lns.lua
Normal file
@@ -0,0 +1,79 @@
|
||||
local cache = {}
|
||||
|
||||
settings.define("lns_client.allow_dynamic_lns_hosts", {
|
||||
description = "Allow dynamic LNS hosts",
|
||||
type = "boolean",
|
||||
default = false
|
||||
})
|
||||
|
||||
settings.define("lns_client.lns_server", {
|
||||
description = "LNS Server Rednet ID",
|
||||
type = "number",
|
||||
default = 8
|
||||
})
|
||||
|
||||
|
||||
function _load_cache()
|
||||
if fs.exists("lns_cache.db") then
|
||||
db = fs.open("lns_cache.db", "r")
|
||||
db_contents = db.readAll()
|
||||
db.close()
|
||||
|
||||
cache = textutils.unserialize(db_contents)
|
||||
end
|
||||
end
|
||||
|
||||
function _save_cache()
|
||||
db = fs.open("lns_cache.db", "w")
|
||||
db.write(textutils.serialize(cache))
|
||||
db.close()
|
||||
end
|
||||
|
||||
function server()
|
||||
local lns_server_id = settings.get("lns_client.lns_server")
|
||||
local allow_dynamic_lns_hosts = settings.get("lns_client.allow_dynamic_lns_hosts")
|
||||
|
||||
if allow_dynamic_lns_hosts then
|
||||
lns_server_id = rednet.lookup("lns", lns_server)
|
||||
if lns_server_id == nil then
|
||||
io.write("LNS Server not found!\n")
|
||||
return nil
|
||||
end
|
||||
end
|
||||
|
||||
return lns_server_id
|
||||
end
|
||||
|
||||
function lookup(remote_hostname)
|
||||
|
||||
_load_cache()
|
||||
if cache[remote_hostname] ~= nil then
|
||||
return cache[remote_hostname]
|
||||
end
|
||||
|
||||
local data = {
|
||||
["action"] = "lookup",
|
||||
["hostname"] = remote_hostname
|
||||
}
|
||||
|
||||
rednet.send(server(), data, "lns")
|
||||
|
||||
while true do
|
||||
id, msg = rednet.receive("lns")
|
||||
if id == lns_server_id then
|
||||
if msg == nil then
|
||||
return nil
|
||||
else
|
||||
cache[remote_hostname] = msg
|
||||
_save_cache()
|
||||
return msg
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function clear_cache()
|
||||
cache = {}
|
||||
_save_cache()
|
||||
print("Cleared cache!")
|
||||
end
|
||||
Reference in New Issue
Block a user