lua-users home
lua-l archive

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

Some clarifications. I was not proposing ? as an operator on its own. I was
proposing ?. as an operator. It doesn't matter much for a simple


is the same as 

    a and a.b

But it becomes useful for deeper references such as:


Which would be roughly equivalent to

    a and a.b and a.b.c

Except that it wouldn't calculate a.b twice. It's potentially even more
useful if we are writing something like:


Since we probably don't want to write this as

    f() and f().b

A somewhat real world example:

    local indexMethod = getmetatable( t ) ?. __index

The equivalent without ?. is:

    local mt = getmetatable( t )
    local indexMethod = mt and mt.__index

Applying it to message send gets one an equivalent to Objective-C's ability
to send messages to nil.


Is almost equivalent to

    a and a:m()

but the and version only returns one value whereas I would define a?:m() as
returning either nothing if a is nil or all of the results from a:m() if a
is not nil.

But as I move to send this, I read Roberto's lovely little solution that
only has the downside of creating empty tables and functions and even that
can be avoided by predefining some globals.

    a?.b    === ( a or {} ) . B
    a?[ b ] === ( a or {} )[ b ]
    f?()    === ( f or function() end )()
    a?:b()  === ( a or { b = function() end } ):b()
        -- Or use a global object that returns the empty function for all
        -- lookups

That just leaves:

    a:b?() -- Send b to a but don't generate an error if it is unsupported

I don't see a way to do this without explicitly saving off a somewhere as

    local temp = a
    ( temp.b or function() end )( temp )

Is this a feature I'm dying to have? No. But it is a case that I've dealt
with more often I might have expected and the solutions become a bit