AgentE382

ComputerCraft Universal File Handle (Broken)

Nov 18th, 2013
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.88 KB | None | 0 0
  1. function UniversalHandle( filename, binary )
  2.     local proxy, readHandle, writeHandle, seekWhence, seekOffset, vBufMode, vBufSize, contents, activeHandle = {}
  3.  
  4.     local function readSetup()
  5.         if io.type(readHandle) ~= "file" then
  6.             if io.type(writeHandle) == "file" then
  7.                 writeHandle:close()
  8.             end
  9.            
  10.             readHandle = io.open(filename, binary and "rb" or "r")
  11.             activeHandle = readHandle
  12.         end
  13.  
  14.         readHandle:seek(seekWhence, seekOffset)
  15.     end
  16.  
  17.     local function read( self, ... )
  18.         readSetup()
  19.         return binary and readHandle:read() or readHandle:read(...)
  20.     end
  21.  
  22.     local function lines( self, ... )
  23.         readSetup()
  24.         return binary and function() return read() end or readHandle:lines(...)
  25.     end
  26.  
  27.     local function close()
  28.         if io.type(readHandle) == "file" then
  29.             readHandle:close()
  30.         end
  31.  
  32.         if io.type(writeHandle) == "file" then
  33.             writeHandle:close()
  34.         end
  35.     end
  36.  
  37.     local function seek( self, whence, offset )
  38.         seekWhence = whence
  39.         seekOffset = offset
  40.  
  41.         return activeHandle:seek(whence, offset)
  42.     end
  43.  
  44.     local function flush()
  45.         if io.type(writeHandle) == "file" then
  46.             writeHandle:flush()
  47.         end
  48.     end
  49.  
  50.     local function setvbuf( self, mode, size )
  51.         vBufMode = mode
  52.         vBufSize = size
  53.     end
  54.  
  55.     local function write( self, ... )
  56.         readSetup()
  57.         readHandle:seek("set")
  58.         contents = read("*a")
  59.         readHandle:close()
  60.        
  61.        
  62.  
  63.         writeHandle = io.open(filename, binary and "wb" or "w")
  64.         activeHandle = writeHandle
  65.  
  66.         if binary then
  67.             local len = #contents
  68.             contents = string.byte(contents, 1, len)
  69.             for i=1, len do
  70.                 writeHandle:write(contents[i])
  71.             end
  72.         else
  73.             writeHandle:write(contents)
  74.         end
  75.  
  76.         writeHandle:seek(seekWhence, seekOffset)
  77.         writeHandle:setvbuf(vBufMode, vBufSize)
  78.  
  79.         writeHandle:write(...)
  80.     end
  81.  
  82.     local proxy = {read = read, lines = lines, close = close, seek = seek, flush = flush, setvbuf = setvbuf, write = write}
  83.  
  84.     return proxy
  85. end
Advertisement
Add Comment
Please, Sign In to add comment