Kingdaro

implement

Nov 17th, 2012
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.40 KB | None | 0 0
  1. --[[
  2.     Author: Kingdaro
  3.     doughnut steel
  4.  
  5.     Description:
  6.     implements the code of another file
  7.     into the top of whatever file(s) you choose
  8.     useful for, as an example, storing a checkFuel() function
  9.     and implementing it into turtle programs
  10.     as opposed to rewriting it every time
  11. ]]
  12.  
  13. local args = {...}
  14.  
  15. local function implement( source, ... )
  16.     local dir = shell.dir()
  17.     source = source..dir
  18.  
  19.     local sourceFile = fs.open(source, 'r')
  20.     if not sourceFile then
  21.         return false, 'could not open source file'
  22.     end
  23.     local code = sourceFile.readAll()
  24.     sourceFile.close()
  25.  
  26.     -- format code for reimplementation if already implemented, for easy updating
  27.     code = '--IMPLEMENT '..source..'\n'..
  28.     code..
  29.     '\n--END'
  30.  
  31.     local files = {...}
  32.     for i=1,#files do
  33.         files[i] = dir .. files[i]
  34.         local file = fs.open(files[i], 'r')
  35.         if file then
  36.             local fileContent = file.readAll()
  37.             file.close()
  38.  
  39.             -- remove current implementation if it exists
  40.             fileContent = fileContent:gsub('%-%-IMPLEMENT '..source..'.-%-%-END\n*', '')
  41.  
  42.             file = fs.open(files[i], 'w')
  43.             file.write(code .. '\n\n' .. fileContent)
  44.             file.close()
  45.  
  46.             print ('successfully written ', files[i])
  47.         else
  48.             print ('could not open ', files[i])
  49.         end
  50.     end
  51. end
  52.  
  53. if #args >= 3 and args[2] == 'into' then
  54.     table.remove(args, 2)
  55.     implement(unpack(args))
  56. else
  57.     print 'Usage: implement <source> into <file> (<file2> <file3> ...)'
  58. end
Advertisement
Add Comment
Please, Sign In to add comment