Advertisement
CaptainSpaceCat

Listener

Jun 6th, 2015
299
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.55 KB | None | 0 0
  1. if not fs.exists("msglist") then
  2.   nFile = fs.open("msglist", "w")
  3.   nFile.writeLine("messages = {}")
  4.   nFile.close()
  5. end
  6.  
  7. function reverseTable(table)
  8.   num = 1
  9.   local result = {}
  10.   for i = #table, 1, -1 do
  11.     result[num] = {}
  12.     result[num][1] = table[i][1]
  13.     result[num][2] = table[i][2]
  14.     num = num + 1
  15.   end
  16.   return result
  17. end
  18.  
  19. function serialize(table)
  20.   local result = "messages = {}\n"
  21.   local revTab = reverseTable(table)
  22.   for i, v in pairs(revTab) do
  23.     result = result .. "messages[" .. tostring(i) .. "] = {}\n"
  24.     for k, e in pairs(v) do
  25.       result = result .. "messages[" .. tostring(i) .. "][" .. tostring(k) .. "] = \"" .. tostring(e) .. "\"\n"
  26.     end
  27.   end
  28.   return result
  29. end
  30.  
  31. while true do
  32.   os.loadAPI("msglist")
  33.   id, message, protocol = nil, nil, nil
  34.   id, message, protocol = rednet.receive()
  35.   print(id, message, "prot", protocol)
  36.   if protocol == "getmsglist" then
  37.     print("getmsglist")
  38.     rednet.send(id, serialize(msglist.messages), "sendmsglist")
  39.   else
  40.     print(message)
  41.     rFile = fs.open("msglist", "r")
  42.     local previous = rFile.readAll()
  43.     rFile.close()
  44.     wFile = fs.open("msglist", "w")
  45.     wFile.write(previous .. "\n")
  46.     wFile.writeLine("messages[" .. #msglist.messages + 1 .. "] = {}")
  47.     wFile.writeLine("messages[" .. #msglist.messages + 1 .. "][1] = \"" .. tostring(id) .. ": " .. tostring(message) .. "\"")
  48.     wFile.writeLine("messages[" .. #msglist.messages + 1 .. "][2] = \"" .. tostring(os.day()) .. ":" .. tostring(os.time()) .. "\"")
  49.     wFile.close()
  50.   end
  51. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement