lua-users home
lua-l archive

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


It would be quite easy for those who want implicit conversations to
turn them on by changing the metatable of string. Could be done
shorter, but this one gives nicer error messages:
do
local smt = debug.getmetatable("")
function smt.__add(a, b) return tonumber(a) + tonumber(b) end
  local an = tonumber(a) or error(a.." used in arithmetic is not a number", 2)
  local bn = tonumber(b) or error(b.." used in arithmetic is not a number", 2)
  return an + bn
end
debug.setmetatable("", smt)
end

Yes, you can argue you can now do it the otherway around and set the
metatable of strings to error()s. But there are two arguments against.
First when having multiple modules it would be easier for modules who
want this kind of implicit behaviour to test for it with pcall and add
this implicitly idiom from above if not, than the other way around,
modules which want to be "clean" on implicit converstoins and change
the default metatable to error(). Secondly turning stuff off by
default, and you can "easily do it youself if needed" fits much more
into the lua overallstyle than the other way.

> On the other hand, if the use of 'tonumber' is compulsory, some
> errors give less informative messages.  Example: in the following
> code, y is supposed to be a string that can be coerced to a number.
> Some bug has caused y to be invalid.

The answer is simply, two wrongs dont make a right. If you convert a
value to a number, and you sure it should be a number, you should use
a technique that will error right away, instead of returning a nil and
error later. >

-- like tonumber() but errors if not number
function asnumber(a)
   return tonumber(a) or error(tostring(a).." of type "..
"..typeof(a).."expected to be a number"), 2)
end

This is a general coding best practice advice, catch errors as soon as
possible and error spectacularly (one of the many brilliances from the
"What To Know BeforeDebating Type Systems" steve linked. (And totally
unrelated I indirectly cite from it ""Any fool can write code that a
computer can understand. Good programmers write code that humans can
understand.")