Lua loadfile not finding a file

6k views Asked by At

I had some lua code with the following line:

JSON = loadfile("JSON.lua")()

The file JSON.lua is in the same directory as the lua code that line came from. This code worked for me for a while, and then, without my changing either the lua source, or the JSON.lua, or permission of any of the files, or the directory from where I was running the lua code, I started getting a nil error on that line. (I simply recall NO relevant changes that could have any impact on the lua code.)

Adding an assert revealed that the error was caused by the file not being found. Playing with file permissions, restarting my machine didn't resolve the issue, and pulling back code that I had checked in and was working perfectly did not resolve the error.

I resolved the error by changing the line above to provide the absolute path to that JSON.lua file.

Is there anything explaining why the code without the absolute path could have worked for a while and then stopped working?

Note: This behavior of working and then not working happened to me twice over a week. I am puzzled and though I have now found a fix, I am really curious as to the explanation for that intermittent behavior.

2

There are 2 answers

3
Doug Currie On BEST ANSWER

Lua uses package.path, whose default value comes from the environment variable LUA_PATH if it is set, as the list of directories to search. You can put . of the front of this list to load files from the current directory, or you can put your files in a path on the list.

0
Roddy On

A late answer on this, as I found exactly the same problem.

First, contrary to the previous answer, loadfile doesn't use the package.path search path. It only looks in the specified directory. And if you don't specify a directory, it only look in the 'current directory'. I can't explain exactly why it stopped working for you, but probably your Lua code is somehow being run with a different 'current directory' than previous.

There are two possible fixes: One is to specify an absolute path to loadfile.

JSON = loadfile("c:\\my_folder\\JSON.lua")()

The alternative fix depends on the particular library you're using, which I suspect is Jeffrey Friedl's Lua JSON lilbrary. Because this supports the newer Lua module mechanism, you can just load the module with require, which does support the package.path search path.

JSON = require("JSON")