lua-users home
lua-l archive

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


On 19/08/2011 9.51, Dirk Laurie wrote:
On Fri, Aug 19, 2011 at 09:37:49AM +0200, Gregory Bonik wrote:
Daniel Hertrich wrote:
I'd like to shorten an if condition such as:

if strCustomPropertyValue == "inbox" or strCustomPropertyValue ==
"today" or strCustomPropertyValue == "thisweek" or
strCustomPropertyValue == "thismonth" or strCustomPropertyValue ==
"thisyear" or strCustomPropertyValue == "later" or
strCustomPropertyValue == "someday" or strCustomPropertyValue ==
"archive"  or strCustomPropertyValue == "otherpersons"  then
...
end

An alternative to the solution with tables is a vararg function:

function is_one_of(value, ...)
     for k, v in ipairs(arg) do
         if v == value then return true end
     end
end

That version works in Lua 5.0 and Lua 5.1, but not Lua 5.2.

This one works in Lua 5.1 and Lua 5.2, but not Lua 5.0.

     function is_one_of(value, ...)
         for k, v in ipairs{...} do
             if v == value then return true end
         end
     end

Dirk




This will avoid a creation and table access. It may be a worth optimization if you call it many times.

function is_one_of(value, ...)
  for i = 1, select( '#', ... ) do
    if value == select( i, ... ) then return true end
  end
  return false  -- remove this line if you are ok with a "nil" retval
end

-- Lorenzo