SHARE
TWEET

ComputerCraft Tutorial: msg_receiver_0_6

hevohevo Mar 18th, 2014 1,215 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. -- ##############################
  2. -- msg_receiver
  3. -- version 0.6
  4. -- (a paired program: msg_sender 0.6, http://pastebin.com/yUgqzL98)
  5. -- http://hevohevo.hatenablog.com/
  6.  
  7. rednet.open("right")
  8.  
  9. function myRefuelAll()
  10.   for i=1,16 do
  11.     turtle.select(i)
  12.     turtle.refuel()
  13.   end
  14.   turtle.select(1)
  15. end
  16.  
  17. function printResults(sender_id, message, tbl_results)
  18.   local exist_status, run_status, err_msg = unpack(tbl_results)
  19.   if exist_status then -- found a function
  20.     if run_status then -- success for running
  21.          print("#",sender_id,": ",message)
  22.     else -- failed or doesn't reply
  23.       print("#",sender_id,": ",message)
  24.       if err_msg then
  25.         print(" (Error) ",err_msg)
  26.       else
  27.         print(" (No reply) ")
  28.       end
  29.     end
  30.   else -- failed with running by wrong string
  31.     print("#",sender_id,": ",message)
  32.     print(" (NotFound) ")
  33.   end
  34. end
  35.  
  36. -- main
  37. while true do
  38.   local sender_id, message, distance = rednet.receive()
  39.  
  40.   -- when a message includes the plural functions, doesn't return values.
  41.   if not string.find(message,";") then
  42.     message = "return "..message
  43.   end
  44.  
  45.   -- make a function and run
  46.   local func = loadstring(message)
  47.   setfenv(func, getfenv()) -- change func's environment(_G) to current one.
  48.   local results = {pcall(func)} -- table: 1) exist_status, 2) run_status, 3) err_msg
  49.  
  50.   -- respond results to the sender
  51.   rednet.send(sender_id, textutils.serialize(results))
  52.  
  53.   -- print results to the terminal display.
  54.   printResults(sender_id, message, results)
  55. end
RAW Paste Data
Top