2

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

Community
  • 1
  • 1
sceiler
  • 1,145
  • 2
  • 20
  • 35
  • 2
    The second answer you cite mentions that error handling should be added to the code... – lhf Apr 15 '15 at 10:23

1 Answers1

1

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.

lhf
  • 70,581
  • 9
  • 108
  • 149
  • Hi, yes I also thought about the file not existing when I checked the IO documentation it stated that nil will be returned for not existing files etc. I just confirmed it with assert() BUT the file exists. I created it and wrote some lines inside. text.txt and my lua script are in the same directory. Does lua look in a different place?? – sceiler Apr 15 '15 at 10:24
  • 3
    @sceiler, the place where the Lua script is is not necessarily the current directory of the application. I don't know what ZeroBrane does. Try running your script from the command line if possible. – lhf Apr 15 '15 at 10:36
  • thanks, that is it. I didn't think about that, shame on me. wors perfectly fine now. Btw. ZeroBrane Studio is an IDE for lua scripts. Similar to Eclipse, Netbeans and VisualStudio. You can run your script like an exe. Really helpful for me who is used to VisualStudio – sceiler Apr 15 '15 at 11:27