Table of Contents

Buffer API

The buffer library provides user friendly streams. These are the kind that the io library returns from io.open unlike the raw streams returned by filesystem.open which don't support as many helpful methods. These helper methods on the file handles you get from io.open are defined here, under Instance Methods. Thus, this API documentation is important and helpful even if you aren't building your own buffered streams.

Additionally, this API allows you to create buffered streams. You provide the backend stream read and write, the buffer library provides the formatting and buffering of the data. Generally, users will not need to make their own buffered streams. For reference, the io library uses buffered streams (which includes file io as well as terminal io)

Static Methods

The following methods are called on the buffer library itself.

Instance Methods

The following methods can only be called on instances created by buffer.new (note file handles returned by io.open are also buffered streams, created with buffer.new). These methods are instance methods, requiring instance call notation :. In order to help differentiate these instance methods from static methods (e.g. buffer.new), b: will be used to prefix the method names.

snippet.lua
local file = io.open("/tmp/foo.txt", "w")
file:write("abc", "def", "\n")
file:close()
-- foo.txt now has "abcdef\n"
snippet.lua
local file = io.open("/tmp/foobar.txt")
for line in file:lines() do
  process_next_line(line)
end
file:close()
snippet.lua
local file = buffer.new("r", { read = function() os.sleep(5) return "a" end })
file:setvbuf("full", 1) -- set buffer size to 1 char
file:setTimeout(1) -- set buffer timeout to 1 second
-- this will time out before trying to read the 2nd char
local a, b = file:read(1, 1) -- read 1 char, then read 1 char again

Interface Methods

The following methods are expected to be implemented on the buffered streams passed to buffer.new.

Examples

Contents