lua-users home
lua-l archive

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


W. C. Bubel wrote:
> It's fairly trivial to turn a large if statement, such as
>   if x == 10 then a()
>   elseif x == 11 then b()
>   elseif x == 12 then c() end
> into a table like this
>   switch = { [10]=a, [11]=b, [12]=c };
>   switch[x](); 
> 
> However, I'm wondering what the table construction might be for a if
> series such as this
>   if x < 10 then a()
>   elseif x == 11 then b()
>   elseif x == 12 then c()
>   else d() end

You can use mutually exclusive filters as keys in your table. Here is an
example:

function switch(filters)
  return setmetatable({}, {__index=function(t, k)
    -- check each filter
    for filter,value in pairs(filters) do
      -- don't test against 'default'
      if filter~='default' then
        -- if filter is a function, call it
        if type(filter)=='function' then
          if filter(k) then
            return value
          end
        -- otherwise just compare keys
        else
          if filter==k then
            return value
          end
        end
      end
    end
    return filters.default
  end})
end
-- 'default' and functions are special keys, use eq"default" or
-- eq(some_func) if you need them

function eq(reference)
  return function(value)
    return value == reference
  end
end
function lt(reference)
  return function(value)
    return value < reference
  end
end
-- add more filters as needed

for _,f in ipairs{'a', 'b', 'c', 'd'} do _G[f] = function() print(f) end
end

local myswitch = switch{[lt(10)]=a, [eq(11)]=b, [12]=c, default=d}

myswitch[5]()  --> a
myswitch[10]() --> d
myswitch[11]() --> b
myswitch[12]() --> c