binser icon indicating copy to clipboard operation
binser copied to clipboard

readFile and writeFile do not return an error

Open MorganPeterson opened this issue 5 years ago • 0 comments

Lua 5.4.0 on Arch Linux

Current readPath and writePath follow a pattern that if the file does not exist it wraps the io.open return value in an assert which then calls Lua's error stack. In one instance this caused me to have to write my own file handling. It would be nice if readFile and writeFile would return nil or an error so I could handle it myself.

A contrived example of the case:

binser = require("binser")
t = { data = "someData"}
data = binser.readFile("myfile")

if data then
  data[#data + 1] = t
end

binser.writeFile("myFile", table.unpack(data))

In my opinion, what I would like to see from readFile/writeFile might be something like this:

local function readFile(path)
  local file, err = io.open(path, "rb")
  if not file then return nil end
  -- assert(file, err)
  local str = file:read("*all")
  file:close()
  return deserialize(str)
end

MorganPeterson avatar Aug 21 '20 14:08 MorganPeterson