[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Res: Switch/Case statements revisited
- From: Sérgio Medeiros <tampo_8@...>
- Date: Fri, 16 Nov 2007 09:58:06 -0800 (PST)
Hi, Steve!
I was trying to use LuaMacros, but it seems there is something wrong
with the parsing of the tokens. I tried this example:
luaf -lmacro -lmacro-defs erro3.lua
_________________
PLUS (44, 33)
a = 33
_________________
It seems a valid Lua program, but I got: erro3.lua:3: syntax error near 'a'
Am I missing something here?
Sérgio
----- Mensagem original ----
De: steve donovan <steve.j.donovan@gmail.com>
Para: Lua list <lua@bazar2.conectiva.com.br>
Enviadas: Quarta-feira, 7 de Novembro de 2007 6:37:56
Assunto: Switch/Case statements revisited
Hi guys,
This is obviously a perenial topic, since there's a wiki page dedicated
to it:
http://lua-users.org/wiki/SwitchStatement
My feeling is that switch is the wrong model; we should look at
Pascal's case statement as more appropriate inspiration. Here are some
possible forms:
case (k)
is 10,11: return 1
is 12: return 2
is 13 .. 16: return 3
else return 4
endcase
......
case(s)
matches '^hell': return 5
matches '(%d+)%s+(%d+)',result:
return tonumber(result[1])+tonumber(result[2])
else return 0
endcase
You can provide a number of values after is, and even provide a range
of values. matches is string-specific, and can take an extra parameter
which is filled with the resulting captures. This is implementable
using token filter macros so people can get a feeling for its use in
practice.
(See http://lua-users.org/wiki/LuaMacro, which has been
semi-officially released - the downloadable source zip contains an
example implementation. Unfortunately, there is a gotcha; Lua
complains of a malformed number if there is no whitespace around
'...'. Also 'result' has to be global. These are implementation
irritations, not relevant to a design discussion, I think),
This case statement is a little bit of syntactical sugar over a chain
of elseif statements, so its efficiency is the same. What the
compiler actually sees in the first case is:
do local __case = k; if false then
elseif __case == 10 or __case == 11 then return 1
...
end; end
But already I've thought of some other possibilities. This feels a
little more elegant.
case (k)
is 10 or 11: return 1
is 12: return 2
is between(13,16): return 3
else return 4
endcase
What do you think?
steve d.
Abra sua conta no Yahoo! Mail, o único sem limite de espaço para armazenamento!
http://br.mail.yahoo.com/