JustDoesGames

lookup

Aug 10th, 2020
1,749
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 2.12 KB | None | 0 0
  1. local args = {...}
  2. local function usage()
  3.     print("Usage:")
  4.     print(" - lookup <name>")
  5.     print(" - lookup list")
  6.     print(" - lookup create/add <name> <location>")
  7.     print(" - lookup delete <name>")
  8. end
  9. if #args < 1 or #args > 3 then -- Just to speed things up a tad bit
  10.     return usage()
  11. end
  12.  
  13. local lookupDir, database = "/l/database.lua", {}
  14. if fs.exists(lookupDir) then
  15.     local f = fs.open(lookupDir, "r")
  16.     if not f then return printError("Failed to load database.") end
  17.     database = textutils.unserialize(f.readAll()) f.close()
  18. end
  19.  
  20. local function lookup(address)
  21.     for i=1, #database do
  22.         if database[i].address == address then return i end
  23.     end
  24.     return false
  25. end
  26.  
  27. if args[1] == "create" or args[1] == "add" then
  28.     if #args ~= 3 then return usage() end
  29.     local tmp = lookup(args[2]) -- To avoid running this twice
  30.     if tmp then return printError("Address already exists") end
  31.     table.insert(database, {address=args[2],location=args[3]}) print("Added '"..args[2].."' to database.")
  32. elseif args[1] == "delete" or args[1] == "del" then
  33.     if #args ~= 2 then return usage() end
  34.     local tmp = lookup(args[2]) -- To avoid running this twice
  35.     if not tmp then return printError("Address does not exist") end
  36.     local tmp2 = database[tmp].address -- For display purposes
  37.     table.remove(database, tmp) print("Deleted '"..tmp2.."' from database.")
  38. elseif args[1] == "list" or args[2] == "ls" then
  39.     print("Database consist of "..#database.." Addresses:")
  40.     for i=1, #database do
  41.         sleep(.1)
  42.         print("Name: "..database[i].address.." | Location: "..database[i].location)
  43.     end
  44.     return database
  45. else
  46.     if #args ~= 1 then return usage() end
  47.     local tmp = lookup(args[1]) -- To avoid running this twice
  48.     if tmp then
  49.         print("Address Exists!")
  50.         print("Name: "..database[tmp].address)
  51.         print("Location: "..database[tmp].location)
  52.         return true
  53.     else
  54.         print("Address '"..args[1].."' does not exists.")
  55.         return false
  56.     end
  57. end
  58.  
  59. local f = fs.open(lookupDir, "w")
  60. if not f then return printError("Failed to save database to '"..lookupDir.."'") end
  61. f.write(textutils.serialize(database)) f.close()
  62. print("Database saved.")
  63.  
  64.  
  65. -- End of Program
Advertisement
Add Comment
Please, Sign In to add comment