[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Suggestion: file:write() and other methods should return file
- From: HyperHacker <hyperhacker@...>
- Date: Sat, 2 Jul 2011 06:35:49 -0600
On Sat, Jul 2, 2011 at 04:56, Marc Balmer <marc@msys.ch> wrote:
> Am 02.07.2011 12:53, schrieb HyperHacker:
>> I just noticed that file:write() returns true on success (though the
>> manual doesn't mention any return value). If it were changed to return
>> the file, you could write:
>>> assert(io.open('foo', 'a+')):write('foooo'):close()
>>
>> instead of:
>>> local file = assert(io.open('foo', 'a+'))
>>> file:write('foooo')
>>> file:close()
>>
>> One simple change allows for much shorter, neater code... seems pretty
>> Lua-ish to me! :) Other file methods such as file:flush() and
>> file:setvbuf() could benefit from the same change. file:seek() as
>> well, but then you'd be breaking the API (you'd have to return file
>> and position instead of just position). file:read() maybe if you have
>> some "read into a table" or "pass the read data to a callback
>> function", but now we're getting kind of out there... :)
>
> How do you catch an error then? Not everyone ignores the return code
> like you do in your example above...
>
>
>
It would still return nil and error message on failure. That does mean
if you write something like I did you'd get an "attempt to index nil"
error, but you can fix that with more assertion (as Rebel Neurofog
showed) or wrapping it in a pcall().
--
Sent from my toaster.