lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


If you find no other solution, you could wrap io.open to make it store the open type in a table like this:

--This goes somewhere very early in your code, before opening any file.
do
    local files={}
    local oldopen=io.open
    function io.open(f,m) 
        local r=oldopen(f,m)
        ___files[r]=m
        return r
    end
    function io.getmode(handle)
        return ___files[handle]
    end
end


t=io.open("/dev/random","r")
--This will print "r".
print(io.getmode(t))
--And probably this would also work but I haven't tested it: t:getmode()


Also you could make the keys of table "files" weak so that when the last reference to the file handle is garbage collected, the corresponding entry in the table will get eventually erased. Although you should NOT rely on when the entry is erased (or when the file handle is garbage collected) to see if the file is still open or if it has been closed because garbage collection could happen quite some time after closing the file yourself. You could of course use both weak keys to erase entries that have been closed and discarded by garbage collection AND wrap io.close too to make it erase the entry if you manually close the file.


On Tue, Oct 23, 2012 at 3:08 AM, Geoff Leyland <geoff_leyland@fastmail.fm> wrote:
Hi,

It's possible to check whether a variable is an open file with io.type.

Is it possible to check whether that file is readable?  Whether it's writeable?  (I know I could try reading or writing to the file, but if it worked the file wouldn't be in the same state any more).

Cheers,
Geoff