lua-users home
lua-l archive

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

Sean Conner <> 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.


   -- 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
      return s

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

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

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...


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