lua-users home
lua-l archive

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


On 23/10/2012 11:41, Konstantinos Asimakis wrote:
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.

Anyway as I understand it files (or ___files) is not accessible to later code (outside the do...end block), is it? So there would be no risk of misuse. Anyway, thank you for the scheme of wrapping builtin features inside such local blocks to customise them, I'll probably reuse it. PS: Once the file (module) where this is defined is loaded, which io.open is accessible to other files (in case the new def belongs to what you export from the defining module)? Both cases would probably be useful...

Denis