lua-users home
lua-l archive

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


On Jul 2, 2011, at 3:56 AM, Marc Balmer 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...

Monadic file error values? In the event of an error, it returns an object containing the error code which supports the same file operations but doesn't actually do anything. (TBD whether it passes through close and flush, it probably should.) Then you write:

io.open( 'foo', 'a+' ):write('fooo'):close():assert()

Here assert is a method that by default returns self but in the case of a monadic error value throws.

I rather like this in some ways, but I'm not particularly fond of having some methods pass through and some not since that makes the spec rather unclear.

Mark