lua-users home
lua-l archive

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


Sean Conner <sean@conman.org> writes:
>> Given an array, produce a "set". local s={}; for _,v in ipairs(a) do
>> s[v]=true done end return s.
>
>   I don't see the reason for this.  The only two values that evaluate to
> false are false and nil.  

It's actually pretty useful, because it allows a nice syntax for
writing fast table-based predicates.

E.g.:

   -- Return a table containing every key in KEYS as a key, with value true.
   --
   local function set (keys)
      local s = {}
      for i,v in ipairs (keys) do
         s[v] = true
      end
      return s
   end

   local keyword_set = set {'if', 'while', 'do', 'end'}

   function some_wacky_parsing_function (...)
      ...
      if keyword_set[token] then
        -- do some keywordy thing
      else
        -- do some other kinda thing
      end
      ...
   end

You could of course just write out:

   local keyword_set = {['if'] = true, ['while'] = true, ...}
   
but it can be kind of nice to use the more concise syntax.

Like most of the mentioned functions it's very simple, so I just
always include a local copy wherever I use it... but maybe some of
them are so widely used they're worth making standard, I dunno...

-miles

-- 
Bride, n. A woman with a fine prospect of happiness behind her.