lua-users home
lua-l archive

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


Depending on how common iterator factories like pairs() are (especially among the metatable-using crowd), this proposal might make more sense:

       --proposed addition
       if type(f)~= "function" then
         local meta_factory = metatable(f).__iter
if not meta_factory and type(f)=="table" then meta_factory = pairs end
         if meta_factory then f, s, var = meta_factory(f) end
       end

(Also, I forgot an "end" to close the "default" conditional - I've added it in the version of the original message as listed below.)

On Mon, 24 May 2010 16:27:41 -0700, Stuart P. Bentley <stuart@testtrack4.com> wrote:

Here's a rewrite based on the manual's definition of the generic for (a better approach):

A for statement like

      for var_1, ···, var_n in explist do block end

is equivalent to the code:

      do
        local f, s, var = explist

        --proposed addition
        if type(f)~= "function" then
          local meta_f = metatable(f).__iter
          if not meta_f and type(f)=="table" then meta_f = next end
          if meta_f then f, s, var = meta_f, f, s end
        end

        while true do
          local var_1, ···, var_n = f(s, var)
          var = var_1
          if var == nil then break end
          block
        end
      end