lua-users home
lua-l archive

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



sorry.. here's the code :o

-----
-- switch construct
--
-- Switch and Lua:  http://lua-users.org/wiki/SwitchStatement
--
-- AK/9-Apr-05: Modified so that 'case' keyword is not required
-- (should also be faster due to less table creation & direct lookup).
--
-- Usage:
--      switch( action, {
--              [DOG_BARK]= do print "Arf!!!" end,
--              [DOG_BITE]= do print "Chomp!" end,
--              [DOG_SLEEP]= do print "Zzzzzz..." end,
--              } ) or print "Default!"
--
-- Note: Use of 'do' above equals 'function()', if "DO_PATCH" is applied.
--       For vanilla Lua 5.x, use the longer "function()".
--
-- Note: Functions are automatically called by 'switch', if they return 'nil' -- the function itself is passed on as the value of 'switch'. This allows
--       using "or" for the default (as above).
--
-- Note: Unlike C's 'switch/case' statement, this actually provides the value, -- too, so it can be used in the way "cond1 ? val1 : cond2 ? val2 : ..."
--       is used in C.  Two flies with one stroke. :)
--
-- Note: The 'key' used may be of any Lua data type.
--
-- WARN: giving a 'false' value in some of the cases will mess up "or" usage -- for default handling. However, "~=nil or ..." will work even then.
--
function switch( key, cases )
    --
    assert(key, "nil key in 'switch'")
    local v= cases[key]

    if type(v)=="function" then
        local v2= v()  -- do we get a return value?
        if v2~=nil then
            return v2   -- value returned by the function
        end
    end
    return v	-- nil (or false) will lead to the default (if any)
end


9.4.2005 kello 19:51, Asko Kauppi kirjoitti:


I revisited the way 'switch' was implemented in LuaX, and here's the code.

This approach is imho more "lua-like" than the earlier, based on Eric Tetz's code was. Also, it only consumes the "switch" keyword, and uses neither "case" nor "default".

Comments are welcome, but for those not being there the "last time" have a look at http://archive.neotonic.com/archive/lua-l/browse_frm/thread/3024/13494 thread first. :)

(oops, that was the 'continue' thread, but there's some on switch about the same time..)


BTW, could "do ... end" be used instead of anonymous non-parameter closures? has anyone done that:

--      switch( action, {
--              [DOG_BARK]= do print "Arf!!!" end,
--              [DOG_BITE]= do print "Chomp!" end,
--              [DOG_SLEEP]= do print "Zzzzzz..." end,
--              } ) or print "Default!"

-ak