Reputation: 375
I am trying to create a file in Lua.
The following threads all say the same thing:
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
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:
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