lua-users home
lua-l archive

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


On 21 March 2011 17:51, Steve Litt <slitt@troubleshooters.com> wrote:
> On Sunday 20 March 2011 15:16:40 Michal Kottman wrote:
>> On Sun, 2011-03-20 at 18:59 +0000, Matthew Wild wrote:
>> > On 20 March 2011 17:41, Matthias Kluwe <mkluwe@gmail.com> wrote:
>> > > Look at the following simple example:
>> > >
>> > > local function f( ... )
>> > >
>> > >    local of = io.open( 'x.txt', 'w' )
>> > >    of:write( ... )
>> > >
>> > > end
>> >
>> > I think it's especially wise to be careful when dealing with files
>> > opened with "w".
>>
>> I use the following "rule of thumb" for dealing with files: when dealing
>> with opening a lot of files (like in a for loop), I close the files by
>> myself using f:close(), otherwise I leave it to Lua GC.
>
> I ALWAYS close files I open. It's a matter of style, it's a matter of self-
> documenting code, it's a matter of maintainability, and as proven in this
> thread, it's a matter of robustness. In the same vain, in C I always free()
> whatever I malloc(), even though I know the memory will be given back on
> program termination.

Indeed. It's a good principle - you never know when somewhere down the
line you or someone else will decide to call your code in a loop.
You're saving that person much time and head-scratching - why a script
works fine sometimes yet sometimes fails with "too many open files" is
a pain to debug. I know, I've been there :)

Matthew