Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function UniversalHandle( filename, binary )
- local proxy, readHandle, writeHandle, seekWhence, seekOffset, vBufMode, vBufSize, contents, activeHandle = {}
- local function readSetup()
- if io.type(readHandle) ~= "file" then
- if io.type(writeHandle) == "file" then
- writeHandle:close()
- end
- readHandle = io.open(filename, binary and "rb" or "r")
- activeHandle = readHandle
- end
- readHandle:seek(seekWhence, seekOffset)
- end
- local function read( self, ... )
- readSetup()
- return binary and readHandle:read() or readHandle:read(...)
- end
- local function lines( self, ... )
- readSetup()
- return binary and function() return read() end or readHandle:lines(...)
- end
- local function close()
- if io.type(readHandle) == "file" then
- readHandle:close()
- end
- if io.type(writeHandle) == "file" then
- writeHandle:close()
- end
- end
- local function seek( self, whence, offset )
- seekWhence = whence
- seekOffset = offset
- return activeHandle:seek(whence, offset)
- end
- local function flush()
- if io.type(writeHandle) == "file" then
- writeHandle:flush()
- end
- end
- local function setvbuf( self, mode, size )
- vBufMode = mode
- vBufSize = size
- end
- local function write( self, ... )
- readSetup()
- readHandle:seek("set")
- contents = read("*a")
- readHandle:close()
- writeHandle = io.open(filename, binary and "wb" or "w")
- activeHandle = writeHandle
- if binary then
- local len = #contents
- contents = string.byte(contents, 1, len)
- for i=1, len do
- writeHandle:write(contents[i])
- end
- else
- writeHandle:write(contents)
- end
- writeHandle:seek(seekWhence, seekOffset)
- writeHandle:setvbuf(vBufMode, vBufSize)
- writeHandle:write(...)
- end
- local proxy = {read = read, lines = lines, close = close, seek = seek, flush = flush, setvbuf = setvbuf, write = write}
- return proxy
- end
Advertisement
Add Comment
Please, Sign In to add comment