2
votes

I am a complete beginner in Lua and only have a bit experience in C#.

At the moment I am usin ZeroBrane Studio as an IDE. I am trying to read a file and print the whole file to console like this:

function readAll(file)
  local f = io.open(file, "rb")
  local content = f:read("*all")
  f:close()
  return content
end

print(readAll("test.txt"))

but I get an error on line 8, which is local content = f:read("*all") with this message: attempt to index local 'f' (a nil value)

What is wrong with my code? I am explicitly not using the lines iterator here.

Btw. I also tried to use these answers by copy-pasting: How to read data from a file in Lua

Reading whole files in Lua

but no luck

1
The second answer you cite mentions that error handling should be added to the code... - lhf

1 Answers

1
votes

The error message means that the file does not exist or cannot be opened.

Use local f = assert(io.open(file, "rb")) to see what error you get.

Or local f, err = io.open(file, "rb") and print or handle err if f == nil.