lua-users home
lua-l archive

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


> case(x){
>    [1] = function() ... end
>    [2] = function() ... end
> }
>
> Should be quite easy to implement.
> Tuomo

True...
function case(x) do
   return function(t) return t[x]() end
end

is simple enough, however, how would one implement the equivalent of...

select case(x)
{
   case 1,2:  ...
   case 3,7:  ...
   case 9:    ...
   case else: ...
}


Hmmm....

Perhaps....

case(x) {
   [1] = function() ... end
   [2] = 1
   [3] = function() ... end
   [7] = 3
   [9] = function() ... end
   [false] = function() ... end
}

implemented as...
function case(x) do
   return function(t)
      -- convert nil to false
      if not x then x = false end

      -- map "case else" "match" to false
      if not t[x] then x = false end

      -- map [2]=1 case to 1
      if t[t[x]] then x = t[x] end

      -- if after "mappings" we have an entry
      -- then call it
      if t[x] then t[x]() end
   end
end

Of course the above does not handle chained "mappings", and after all of it
you're probably better off just writing the table construction and its use
in line rather than using the "case" function --as it would be clearer to
Lua programmers--, but it was an interesting exercise.

Thanks.