lua-users home
lua-l archive

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



On 5-Feb-05, at 9:51 AM, Javier Guerra wrote:

in short, i'd like that
(nil)[anything] == nil
instead of failing

does anybody object to this?

The reasonable objection is that this would serve to hide
programming errors, although I personally could live with
it. However, it might be worthwhile considering alternatives.

For example, it would be possible to define the following
syntaxes:
  table?key
  table?[expr]
  func?(args)
and so on, which would declare that the programmer anticipated
that the left hand expression might evaluate to nil or false,
in which case the value should be the left hand expression.
This could optionally short-circuit the evaluation of the
entire sequence of postfix operators, so that:

  t?foo.bar

would effectively mean that 'foo' might not be a key of t, but
if it is, it must itself have a 'bar' key, which some might
find intuitive.

Another option, which has also been suggested from time to time,
is to add some sort of __toboolean metamethod, which would allow
the creation of an object which behaved the way you are suggesting
'nil' behave. Then you could attach that object as a default value
for a table which you wished to have that sort of behaviour:

  NOVALUE = {}
  do
    local novalue_meta = {}
    function novalue_meta:__index() return NOVALUE end
    function novalue_meta:__toboolean() return false end
    setmetatable(NOVALUE, novalue_meta)

    local opt_meta = {}
    function opt_meta:__index() return NOVALUE end

    function OptTable()
      return setmetatable({}, opt_meta)
    end
  end

Yet another interesting possibility is an extension to the
syntax of 'if' (and maybe 'while') to create a local:

  if subtable = table[index] then
    -- subtable is in scope in this chunk
    var = subtable.field
   else
    -- subtable is not in scope here
    var = nil
  end