lua-users home
lua-l archive

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


Le sam. 11 sept. 2021 à 10:51, Petri Häkkinen <petrih3@gmail.com> a écrit :
On 11 Sep 2021, at 9.55, Philippe Verdy <verdyp@gmail.com> wrote:
> Isn't the error generated by "type()" superfluous when it is called with no argument at all? Shouldn't it simply return nil so that "type(('A'):byte(2))" will safely also return nil without any error?

Nope. 'type' is a function that expects one argument. How is this any different from, say, math.sin? Would you expect math.sin() to return 'nil' as well?

Nope, because nil (or string 'nil') is not a valid return value for math.sin. But type() can safely return the string 'nil' (not the value nil) without error: it matches its definition: the code expects the return value to be a string, so that the code does not need to check the type of value returned by type(anything), and also does not need to catch errors by using:
   local ok,str=pcall(type,anything).


Generally speaking, it's good that functions expecting one argument raise an erorr when given zero arguments. That helps catching bugs earlier.

Here this does not help catching any bug. This generates unexpected errors that are hard to understand when we've actually passed an _expression_ in its arguments.
And why then type(1,2) does not generate an error but just returns "number" (you've called it with two arguments instead of one, the second is silently ignored: type() does not require any fixed number of arguments, does not use varargs, it just check the type of its first argument which may already be a nil value and thus not even actually passed by the caller)

You can already write: function fun(x) return x end
and call it with: fun(1) which returns 1; or fun(1,2) which also returns 1; or fun() which returns nil !
That function can be called with any parameters, it just returns the 1st argument (if there's any), or nil otherwise.