I have a function in a Lua script, that will take a file and and will work on it. Part of the work it does is to empty the file completely before working with it. The easiest way I know of doing this is to open the file with io.open , and use the "w+" parameter. The problem is that I always need to have the path to the file. I wanted to do this:

io.open(thefile, "w+"); -- here thefile is a file object

but of course, that doesn't work. I need a way to get a file path in Lua. Anyone got suggestions? Sorry if I posted this in the wrong forum :/

So if I'm reading this right, you have a file handle that was returned by io.open at some previous point, but you need the filename that was used to create the handle so you can truncate it. Yes?

For now, I'm assuming that we're talking about Lua 5.1.4 because it's the current release. Are you using anything older than 5.1?

The io library doesn't provide anything that can truncate a file, so it looks like you're on the right track with io.open("somefile.ext", "w+") if you need a 100% standard Lua solution.

I don't think Lua can help you directly on this one. io.open doesn't keep the filename around, so you'll need to keep track of the filename when you open it. The file handles that io.open returns are userdata objects, which you can't modify from Lua, so you can't just stick the filename string in the file handle, either. I think we're left with creating some sort of custom file object--at its simplest, it could be a table with two entries, one for the filename, and one for the file handle.

This article has been dead for over six months. Start a new discussion instead.