maxthewell

net.lua

Aug 22nd, 2019
166
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.10 KB | None | 0 0
  1. SIDES = {"left", "right", "top", "bottom", "front", "back"}
  2.  
  3. local modem = nil
  4.  
  5. function connect()
  6.     if modem ~= nil and rednet.isOpen(modem) then
  7.         return true
  8.     end
  9.     for _, side in ipairs(SIDES) do
  10.         if peripheral.getType(side) == "modem" then
  11.             rednet.open(side)
  12.             if rednet.isOpen() then
  13.                 modem = side
  14.                 return true
  15.             end
  16.         end
  17.     end
  18.     error("could not establish connection")
  19.     return false
  20. end
  21.  
  22. function broadcast(msg, proto)
  23.     connect()
  24.     rednet.broadcast(msg, proto)
  25. end
  26.  
  27. function getID(host, proto)
  28.     connect()
  29.     id = rednet.lookup(proto, host)
  30.     if id == nil then
  31.         error("no such host '" .. host .. "'")
  32.     end
  33.     return id
  34. end
  35.  
  36. function sendToHost(msg, proto, host)
  37.     connect()
  38.     id = getID(host, proto)
  39.     rednet.send(id, msg, proto)
  40. end
  41.  
  42. function listen(proto, id)
  43.     connect()
  44.     while(true) do
  45.         local senderID, msg = rednet.receive(proto)
  46.         if id == nil or id == senderID then
  47.             return senderID, msg
  48.         end
  49.     end
  50. end
Add Comment
Please, Sign In to add comment