Lua - File Buffers and Flushing



In Lua, we can use buffering effectively in File I/O using setvbuf() and flush methods.

Syntax - setvbuf() method

file:setvbuf (mode, [size])

Where file represents the file handle returned by io.open() method and mode can accept following values−

  • no− no buffering. It means output operation result will appear immidiately without buffering.

  • full− full buffering. It means output operation result will appear when buffer is full or flush() method is called explicitly.

  • line− line buffering. It means output is buffered till new line is output.

size is an optional parameter. By default, Lua gives size an appropriate value as per system implementation. It represents the buffer size.

Syntax - flush() method

Simple Model
io.flush ()

flush() method saves any written data to the file.

Complete Model
file:flush ()

flush() method saves any written data to underlying file and file is the handle returned by io.open() method.

Example - Use of setvbuf() and flush() method in Simple Model

Let us now see how to write a file.

main.lua

-- write a file content
function writeFile()
   -- Opens a file in write mode,
   -- create file if not present
   -- overwrite content of file if present
   f = io.open("example.txt","w")
   --set f as default output
   io.output(f)

   -- set the buffer size of 8K
   size = 2^13
   f:setvbuf("full", size)
   -- write the contents
   io.write("Welcome to tutorialspoint.com", "\n")
   io.write("Simply Easy Learning", "\n")

   -- flush the written Output
   io.flush()
   -- close the file handle
   io.close(f)
end

-- write the file
writeFile()

print("Content written to the file successfully.")

Output

When the above code is built and executed, it produces the following result −

Content written to the file successfully.

Example - Use of setvbuf() and flush() method in Complete Model

Let us now see how to write a file.

main.lua

-- write a file content
function writeFile()
   -- Opens a file in write mode,
   -- create file if not present
   -- overwrite content of file if present
   f = io.open("example.txt","w")

   -- set the buffer size of 8K
   size = 2^13
   f:setvbuf("full", size)
   -- write the contents
   f:write("Welcome to tutorialspoint.com", "\n")
   f:write("Simply Easy Learning", "\n")

   -- flush the written Output
   f:flush()
   -- close the file handle
   f:close()
end

-- write the file
writeFile()

print("Content written to the file successfully.")

Output

When the above code is built and executed, it produces the following result −

Content written to the file successfully.
Advertisements