lua-users home
lua-l archive

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



On 20-Sep-06, at 3:55 AM, Philippe Lhoste wrote:
But more Lua like would be:
a = { a = 1,
      b = { b = 2,
            c = {native = 1, rock = 2}[style] or 0
          }
    }

Argh! WOULD BE! I tried it, and wondered by I had syntax errors...
Indeed, it seems a bit strange at first, but it is quite elegant in its simplicity (and no new keyword...).

This is the version which works with current Lua (5.1.1):

> style="native"
> a = { a = 1,
      b = { b = 2,
            c = ({native = 1, rock = 2})[style] or 0
          }
    }
> =a.b.c
1

The parentheses are necessary because of an obscure syntactic issue, although it doesn't apply in that particular context. It's the same reason you need to use:

  ("%d"):rep(#t):format(unpack(t))

instead of the possibly more natural

   "%d":rep(#t):format(unpack(t))

(The former was the answer to a question on IRC the other day: how do I turn a
table which looks like {1, 2, 0, 9, 7, 5} into the string "120975".)

R.