Advertisement
melzneni

global_net

Apr 24th, 2020
140
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.58 KB | None | 0 0
  1. function split(s, delimiter)
  2. local result = {};
  3. for match in (s .. delimiter):gmatch("(.-)" .. delimiter) do
  4. table.insert(result, match);
  5. end
  6. return result;
  7. end
  8.  
  9. rednet.open("top")
  10.  
  11.  
  12. function receiveRednet()
  13. while true do
  14. local id, msg = rednet.receive()
  15. if type(msg) == "string" then
  16. if string.find(msg, ":") ~= nil then
  17. if string.sub(msg, 1, 1) == "[" then
  18. local ind = string.find(msg, "]")
  19. id = tonumber(string.sub(msg, 2, ind - 1))
  20. msg = string.sub(msg, ind + 1)
  21. end
  22. return id, msg
  23. end
  24. end
  25. end
  26. end
  27.  
  28. function getMsgData(msg)
  29. local i, j = string.find(msg, ":")
  30. local tag = string.sub(msg, 1, i - 1)
  31. local pts = split(string.sub(msg, i + 1, -1), ",")
  32. return tag, pts
  33. end
  34.  
  35. local others = {}
  36. local clients = {}
  37.  
  38. function sendToClients(msg)
  39. for _, sid in ipairs(clients) do
  40. rednet.send(sid, msg)
  41. end
  42. end
  43.  
  44. rednet.broadcast("@globalNet:register,startup")
  45.  
  46. rednet.broadcast("@globalClients:register")
  47.  
  48. while true do
  49. local id, msg = receiveRednet()
  50. local tag, pts = getMsgData(msg)
  51. if tag == "@globalNet" then
  52. if pts[1] == "access" then
  53. local alreadyRegistered = false
  54. for _, cid in ipairs(clients) do
  55. if cid == id then
  56. alreadyRegistered = true
  57. break
  58. end
  59. end
  60. if not alreadyRegistered then table.insert(clients, id) end
  61. rednet.send(id, "@gNetAnsw:hu")
  62. elseif pts[1] == "broadcast" then
  63. msg = string.sub(msg, #tag + 1 + #pts[1] + 2)
  64. if string.sub(msg, 1, 1) ~= "[" then
  65. msg = "[" .. id .. "]" .. msg
  66. end
  67. sendToClients("<global>" .. msg)
  68. for _, sid in ipairs(others) do
  69. rednet.send(sid, "@globalNet:broadcastSent," .. string.sub(msg, #tag + 1 + #pts[1] + 2))
  70. end
  71. elseif pts[1] == "broadcastSent" then
  72. print(id)
  73. sendToClients("<global>" .. string.sub(msg, #tag + 1 + #pts[1] + 2))
  74. elseif pts[1] == "register" then
  75. table.insert(others, id)
  76. if pts[2] == "startup" then
  77. rednet.send(id, "@globalNet:register")
  78. end
  79. else error("unknown message: ", msg)
  80. end
  81. end
  82. end
  83.  
  84. --pastebin run 0YB9PsQV startup={files={global=<pb:Y7X9sjQb>},cmds={{'global'}}} reboot=true label=<input:'Label'>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement