lua-users home
lua-l archive

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



You can use 'assert' in many cases:

f = assert(io.open('foo.foo', 'r'))
assert(f:write("xyzzy"))
assert(f:close())

Gé


On Tue, 6 Sep 2011, Dirk Laurie wrote:

On Tue, Sep 06, 2011 at 08:39:00AM +0200, HyperHacker wrote:
Lua 5.1.4  Copyright (C) 1994-2008 Lua.org, PUC-Rio
f=io.open('foo.foo', 'r')
f:write('ffd')
f:close()


Call me crazy, but I feel like f:write() should throw an error when
trying to write to a read-only file, instead of just doing nothing.

There are two ways of handling errors: testable return values, and
throwing errors.  Among programming languages that I use, Lua is unique
in giving you a seamless way of overriding whatever default choice it
has made.  So you can do this:

local io_write = io.write
io.write = function(...)
   local test, message, code = io_write(...)
   if test==nil then error(message,2) end
   end

If io.write had thrown an error instead, you could similarly have
overridden it by a wrapper that uses pcall.

Dirk