Atom
Atom

Reputation: 375

(Lua 5.2) Cannot create file because io.open returns nil file handle

I am trying to create a file in Lua.

The following threads all say the same thing:

  1. https://forum.rainmeter.net/viewtopic.php?t=10024
  2. Create a new file in Lua/LuaFileSystem
  3. Sifteo: how to create a file.txt with LUA script?
  4. Creating new files with Lua I/O functions

They say to use:

local file = io.open("test.txt", "w")
file:write("Hello World")
file:close()

I have implemented this like so:

local ADDRESSES = "capi/addresses.cfg"

local file, err = io.open(ADDRESSES, "w")
local data = "<DATA>"
file:write(data)
file:close()

This, however, results in the error Attempt to index local 'file' (a nil value). This is, of course, because the file does not exist because I am trying to create it. The examples seem to say that the file should be automatically created when I try to write to it, but how can I do that if the handle is nil!?

Upvotes: 0

Views: 939

Answers (1)

Luatic
Luatic

Reputation: 11171

It is correct that io.open(filename, "w") will create the file if it doesn't already exist.

However, there are at least three prerequisites common to file operations:

  1. You must have sufficient permissions to create the file in the desired path (e.g. write permission in the folder)
  2. All folders along the path must already exist. Lua will not create folders for you.
  3. There must be sufficient space (your file system may not be full)

You are presumably not meeting one of the prerequisites. To find out which, simply wrap your call to io.open with assert:

local file = assert(io.open(ADDRESSES, "w"))

Now if opening/creating the file fails, Lua will throw an error that tells you which prerequisite you failed to meet.

In your case, I would consider it most probable that the capi directory doesn't exist yet. On my Linux system, the corresponding error message is capi/addresses.cfg: No such file or directory.

Upvotes: 2

Related Questions