I am learning Lua with youtube video and it introduces a way to write a text file like this:
io.output("myfile.txt")
print("My name is David") -- This won't write into the file, just print to the console
io.write("hello world, how are you\n")
io.write("hello world, how are you\n")
io.write("hello world, how are you\n")
io.write("hello world, how are you\n")
io.close()
Then it introduces a way to read text file like this:
io.input("myfile.txt")
print(io.read("*all"))
io.close()
These two code blocks works when they are in the separate lua files. However, when I combine these two code blocks into a single lua file. It generates an error.
The combined file looks like this:
-- Write file and close it
io.output("myfile.txt")
print("My name is David") -- This won't write into the file, just print to the console
io.write("hello world, how are you\n")
io.write("hello world, how are you\n")
io.write("hello world, how are you\n")
io.write("hello world, how are you\n")
io.close()
-- Read file and close it
io.input("myfile.txt")
print(io.read("*all"))
io.close()
and it shows an error when i run this file:
lua54: file.lua:36: attempt to use a closed file
stack traceback:
[C]: in function 'io.close'
file.lua:36: in main chunk
[C]: in ?
The output that I expect is:
My name is David
hello world, how are you
hello world, how are you
hello world, how are you
hello world, how are you
In the meantime I also tried to delete the first io.close()
so the code looks like this:
-- Write file and close it
io.output("myfile.txt")
print("My name is David") -- This won't write into the file, just print to the console
io.write("hello world, how are you\n")
io.write("hello world, how are you\n")
io.write("hello world, how are you\n")
io.write("hello world, how are you\n")
-- Read file and close it
io.input("myfile.txt")
print(io.read("*all"))
io.close()
But the console output only shows the print()
statement:
My name is David
I also tried to keep the first io.close()
and delete second io.close()
. I got the expected output.
The code looks like this:
-- Write file and close it
io.output("myfile.txt")
print("My name is David") -- This won't write into the file, just print to the console
io.write("hello world, how are you\n")
io.write("hello world, how are you\n")
io.write("hello world, how are you\n")
io.write("hello world, how are you\n")
io.close()
-- Read file and close it
io.input("myfile.txt")
print(io.read("*all"))
Output:
My name is David
hello world, how are you
hello world, how are you
hello world, how are you
hello world, how are you
Could anyone explain why there is an error and what do these codes do, Thanks!
io.close()
closes the default output file.
To close the default input file, use io.close(io.input())