SHARE
TWEET

ComputerCraft Tutorial: logging_API_0_2

hevohevo Jun 7th, 2014 1,167 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. --############################
  2. -- logging API
  3. -- version 0.2b
  4. -- http://hevohevo.hatenablog.com/
  5.  
  6. -- ### how to use
  7. --[[
  8. os.loadAPI("logging")
  9.  
  10. -- default logfile name is "mylog"
  11. logging.forward() -- turtle.fowrard() and logging
  12. logging.back()
  13. logging.up()
  14. logging.down()
  15. logging.turnRight()
  16. logging.turnLeft()
  17.  
  18. -- change logfile
  19. logging.changeLogfile("mylog2")
  20.  
  21. -- write a log forcibly
  22. logging.write("-- my message!!")
  23.  
  24. -- createLoggedFunc(function, succeeded_log, *failed_log)
  25. -- return a function which writes succeeded/failed msg to a logfile
  26. -- if you omit "failed_log" argument, succeeded_log is written in true/false cases
  27. myRefuel = logging.createLoggedFunc(turtle.refuel, "turtle.refuel()")
  28. myRefuel()
  29. --]]
  30.  
  31. -- ###########################
  32. -- config
  33. local logfile_name = "mylog"
  34.  
  35. -- ###########################
  36. -- functions
  37. function changeLogfile(name)
  38.   logfile_name = name
  39. end
  40.  
  41. function write(message)
  42.   local fh = fs.open(logfile_name, "a")
  43.   fh.writeLine(message)
  44.   fh.close()
  45. end
  46.  
  47. -- return a function which writes succeeded/failed msg to a logfile
  48. function createLoggedFunc(func, succeeded_log, failed_log)
  49.   failed_log = failed_log or succeeded_log
  50.   return function()
  51.     local status, error_msg = func()
  52.     if status then
  53.       write(succeeded_log)
  54.     else
  55.       write(failed_log)
  56.     end
  57.     return status, error_msg
  58.   end
  59. end
  60.  
  61. -- redefine six movement functions in Turtle API
  62. forward = createLoggedFunc(turtle.forward, "turtle.forward()", "-- turtle.forward()")
  63. back = createLoggedFunc(turtle.back, "turtle.back()", "-- turtle.back()")
  64. up = createLoggedFunc(turtle.up, "turtle.up()", "-- turtle.up()")
  65. down = createLoggedFunc(turtle.down, "turtle.down()", "-- turtle.down()")
  66. turnRight = createLoggedFunc(turtle.turnRight, "turtle.turnRight()")
  67. turnLeft = createLoggedFunc(turtle.turnLeft, "turtle.turnLeft()")
  68.  
  69. -- ###########################
  70. -- main
  71.  
  72. -- backup "logfile_name", if same name file exists
  73. if fs.exists(logfile_name) then
  74.   -- backup file is "XXXX.bak"
  75.   local bak_file = logfile_name..".bak"
  76.   if fs.exists(bak_file) then fs.delete(bak_file) end
  77.   fs.move(logfile_name, bak_file)
  78. end
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top