fileluanulllua-loadfile

Lua loadfile not finding a file


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.


Solution

  • 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.