lua-users home
lua-l archive

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

The Lua builtin function "type(value)" unexpectedly signals an error (sometimes but not always) when the argument value is nil.

This occurs when the value nil is the result of a function call, and not a simple variable containing nil or the constant nil. This is incoherent !

That error is wrong. `type(nil)` or `type()` or `type(f())` (where `f()` returns nil or nothing), or `type(nil, 'dummy')` or `type(...)` (called from inside a function called without parameters or with a nil parameter in first position of the varaible argument list) should return 'nil' in all cases.

E.g. run in a Lua console:

val = ('A'):byte(1); typ = type(val); print typ ..'=' ..  tostring(val); print type(('A'):byte(1))
--> number=65
--> number
val = ('A'):byte(2); typ = type(val); print typ .. '=' .. tostring(val); print type(('A'):byte(2))
--> nil=nil
--> Error: bad argument #1 to 'type' (value expected).

The problem is that `('A':byte(2)` actually does not return `nil` in its list of upvalues, it just returns an empty list:
* when assigning an empty list to a variable, that variables get `nil` (with the correct type).
* when passing the empty list returned by a function to `type()`, this function gets no parameter and incorrectly signals an "error".

Yes the builtin `type(value)` function "requires" at least one argument, but that argument in first position CAN be `nil`. So it may not be passed at all and the first argument should be initialized with the `nil` value, and the builtin `type(value)` function SHOULD return the string `"nil"`, without any error (which I think is a very legacy behavior of very old versions of Lua before major changes in how lists of values were passed and returned through function calls).

And the builtin `string.byte(index)` function SHOULD also be fixed to return a true `nil` for a given index past the end of string, and not an empty list (or this should not make any difference for calling type()).