Lua File Handling

Viewed 371

I got this error recently:

lua: Lua Testing.lua:36: bad argument #1 to 'read' (invalid option)
stack traceback:
        [C]: in function 'read'
        Lua Testing.lua:36: in main chunk
        [C]: ?

And I'm not sure why. Here's my code:

file = assert(io.open("test.txt", "r"), "no file.")
print(io.read(file))
io.close(file)

To explain a few things, I'm using assert to make sure the file is there and it is. I'm pretty new to Lua. I've googled about this error and I came up with nothing that helped me fix this.

1 Answers

You are using the result of io.open incorrectly.

After you open a file, you can read from it or write to it with the methods read/write. They are similar to the read/write functions, but you call them as methods on the file handle, using the colon syntax. For instance, to open a file and read it all, you can use a chunk like this:

   local f = assert(io.open(filename, "r"))
   local t = f:read("*all")
   f:close()

–Programming in Lua: 21.2 – The Complete I/O Model


Also you did not get a very good error message, my IDE gave me:

so_test2.lua:2: bad argument #1 to 'read' (string expected, got FILE*)
stack traceback:
    [C]: in function 'io.read'
    so_test2.lua:2: in main chunk
    [C]: in ?

You can see in this error string, it tells us specifically that the function expected a string and it was provided a FILE*(a file handle)


Programming in Lua is a great resource while learning Lua.

Related