lua-users home
lua-l archive

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

Tim Kelly wrote:
match k
  with 10, 11 then return 1 end
  with 12 then return 2 end
  with i if 13<=i and i<=16 then return 4 end
While in C and other languages that get compiled into machine code, I can
understand a fixed value that can be used for jump instructions, in an
interpreted language like Lua where speed is not the highest priority,
having more flexibility is reasonable.

Yes, but you don't want to sacrifice speed unnecessarily. The advantage of the above syntax is that it's entirely obvious to the compiler when you're matching against a specific item (with <expr> [, <expr>...] then) or against an expression (with <varname> if). This makes it trivial for, say, the JIT to construct real jump tables.

It also allows you to define different ordering semantics. If you specify that the expressions in a match can be evaluated in any order, and that it's the responsibility of the user to make sure that they're not ambiguous, it makes the compiler's job much easier.

I suspect it'd be easy to implement an approach that has a list of
statements to be evaluated and then the first one in the list that
evaluates "true" is the index to the block of code that gets executed.  It
can also superset the above match syntax inherently:

That would be the obvious basic implementation, but doing it like this doesn't really give much advantage over chained if...elseif statements.


In Case of
     @(10 <= k <=11)
               then return 1
     @(k== 12)
               then return 2
     @(z == 0)
               then return 0
     @((k == i) && ( 13<= i <=16))
              then return 4
        then return 99
end almost identical to:

if (10 <= k) and (k <= 11) then return 1
elseif (k == 12) then return 2
elseif (z == 0) then return 0
elseif ((k == i) and (13 <= i) and (i <= 16) then return 4
else return 99

(I should also point out that 10 <= k <= 11, while nice for the user, is an utter nightmare for the grammar --- unless you declare an entirely new syntax specifically for use in this situation, it can't decide whether you mean a range check or the expression (10 <= k) <= 11... which is completely legal. Although is likely to produce a run-time error.)

Also, Asko's version
didn't match David Given's version, as his version requires (as I read it)
for k to equal i as well as i be between 13 and 16, instead of k being
between 13 and 16.

Yeah, what I meant was that i would be a new local variable containing the value of k in whose scope the if statement was evaluated.

Of course, none of this is ever going to happen... but it's a slow Friday.

David Given