Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect file opening error on Lua

Tags:

lua

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?

like image 624
Hola Soy Edu Feliz Navidad Avatar asked Feb 10 '14 15:02

Hola Soy Edu Feliz Navidad


People also ask

How do you catch errors in Lua?

One method to handle errors in Lua column map procedures is to encapsulate your code in the pcall (protected call) function. When there is an error, the pcall function returns a table object that contains the error code and error message.

What is assert in Lua?

Lua assert is the function to use in the error handling of the Lua programming language. This is the function helping to handle the runtime error of the Lua source code to avoid complications between compile-time error and run time error.

What is IO read in Lua?

The call io. read("*all") reads the whole current input file, starting at its current position. If we are at the end of file, or if the file is empty, the call returns an empty string.


1 Answers

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

like image 85
Tim Cooper Avatar answered Sep 21 '22 16:09

Tim Cooper