Jt Maston
Jt Maston

Reputation: 15

File not working in Lua

I am doing a small program for school in Lua, but I need help. I open a file, but when I write, nothing appears in the .txt file. Can anyone help? This is the snippet of code I am trying to fix:

file=io.open('var.txt',"w+")
     io.output(file)
     io.write('hi!')

Edit: I tried file:close() and io.flush(), but I haven't managed to make it work.

Upvotes: 0

Views: 920

Answers (1)

forty_two
forty_two

Reputation: 534

Try the following:

io.output('var.txt')
io.write('hi!')
io.close()

The function io.output allows you to specify a current file for output by its filename. In your example, you were passing a file handler that you created with io.open instead of a filename. This implicitly creates a bad file handler that io.write cannot use.

For more info, check out the chapter on "The Simple I/O Model" from "Programming in Lua".

Upvotes: 1

Related Questions