5

I'm using Lua on iOS and I'm having problems to open a file with io.open("filename.txt","w"), I know that I'm receiving nil, but is there any way to detect the failure reason and try to solve it according to that? something like errno of C?

1 Answers1

10

From the documentation:

io.open (filename [, mode])

This function opens a file, in the mode specified in the string mode. It returns a new file handle, or, in case of errors, nil plus an error message.

An example usage using the second value returned from the function is as follows:

local f, err = io.open("filename.txt", "w")
if f then
    -- do something with f
else
    print("Error opening file: " .. err)
end

If the process does not have permission to open the file, for example, the following message will be printed out:

Error opening file: filename.txt: Permission denied

Community
  • 1
  • 1
  • I'd like to add that it is *very* important to check the return value of `io.open` before writing anything to the file; actually, if it returns `nil` and you pass this `nil` value as file handle for writing, Lua5.2 segfaults. – michaelmeyer Feb 12 '14 at 22:39