Advertisement
mc1030

chat.lua

Nov 21st, 2020 (edited)
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 2.08 KB | None | 0 0
  1. -- idea: split off two functions one to listen and one to type
  2.  
  3. args = {...}
  4.  
  5. STD_PING_CHAN = 5
  6. STD_REPLY_CHAN = 1
  7. MODEM_SIDE = "left"
  8. local listeningChan
  9. local replyChan
  10.  
  11.  
  12.  
  13. function setup()
  14.     if #args >= 3 then
  15.         replyChan = args[2]
  16.         listeningChan = args[1]
  17.     else
  18.         if #args == 2 then
  19.             listeningChan = args[1]
  20.         else
  21.             listeningChan = STD_PING_CHAN
  22.         end
  23.         replyChan = STD_REPLY_CHAN
  24.     end
  25.  
  26.     print("Set up to listen on: " ..tostring(listeningChan).. " and reply on: " ..tostring(replyChan).. ".\n")
  27.     write("Name: ")
  28.     name = read()
  29.  
  30. end
  31.  
  32. function send(modem)
  33.     term.setTextColor(colors.white)
  34.     write("You: ")
  35.     local input = read()
  36.     if input == "quit" or input == "exit" then
  37.         exitChat(modem)
  38.     end
  39.     modem.transmit(listeningChan, replyChan, name..": "..input)
  40.     receiveReply(modem)
  41. end
  42.  
  43. function receiveReply(modem)
  44.     modem.open(replyChan)
  45.     local event, side, senderChan, replyChan, message, dist = os.pullEvent("modem_message")
  46.     term.setTextColor(colors.lightBlue)
  47.     print("\t\t"..message)
  48. end
  49.  
  50. function cursorToStart(textColor)
  51.     term.setTextColor(textColor)
  52.     term.clearLine()
  53.     x,y = term.getCursorPos()
  54.     term.setCursorPos(1, y)
  55. end
  56.  
  57. function receive(modem)
  58.     modem.open(listeningChan)
  59.     local event, side, senderChan, replyChan, message, dist = os.pullEvent("modem_message")
  60.     cursorToStart(colors.green)
  61.     print(message)
  62.     reply(modem)
  63. end
  64.  
  65. function reply(modem)
  66.     modem.transmit(replyChan, listeningChan, "<.>\n")
  67. end
  68.  
  69. function exitChat(modem)
  70.     print("Exiting chat.\n")
  71.     modem.transmit(listeningChan, replyChan, name.." left the chat.\n")
  72.     error()
  73. end
  74.  
  75. function run()
  76.     local modem = peripheral.wrap(MODEM_SIDE)
  77.     term.clear()
  78.     term.setTextColor(colors.white)
  79.     print("Entered chat. type quit or exit to terminate.\n")
  80.     while true do
  81.         parallel.waitForAny(function()
  82.             send(modem)
  83.         end, function()
  84.             receive(modem)
  85.         end)
  86.     end
  87. end
  88.  
  89. setup()
  90. run()
  91.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement