Jason Garvey
Jason Garvey

Reputation: 49

Attempt to index local 'file' (a nil value)?

I'm doing a project in corona simulator that involves reading some data in from a csv file ("car.csv") that is in the project directory, I have this code that is supposed to read the first line in, but when I run it it gives me the error "Attempt to index local 'file' (a nil value)". Any idea how I can fix this?

local function init()
    local path = system.pathForFile( "car.csv", system.DocumentsDirectory );
    local file = io.open(path, "r");
    line = file:read();
    print(line);
end

For some reason it won't read it in to 'file'.

Edit: Ok if I use the full path rather than the relative file path it works. But I need to use the relative one and I don't know why it doesn't work.

Upvotes: 1

Views: 4000

Answers (1)

DarkWiiPlayer
DarkWiiPlayer

Reputation: 7064

When using io.open, you should always make sure that it actually succeeded before trying to read the file, or you will get an ugly "attemp to index nil" error.

If you want your program to still crash, just do

local file = assert(io.open(path, 'r'))

And it will give you a more helpful error message if the file can't be found. Alternatively, you could also manualle save the return values of io.open and check for errors:

local file, err, code = assert(io.open(path))
if not file then
   print("Error opening file", path, err)
   -- Do something to handle the error
end

Upvotes: 3

Related Questions