lua-users home
lua-l archive

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


On Mon, 24 May 2010, Jonathan Castello wrote:

> On Mon, May 24, 2010 at 2:57 PM, M Joonas Pihlaja
> <jpihlaja@cc.helsinki.fi> wrote:
> > I'm slightly wary of your proposal because it 1) adds even more
> > implicit magic to the language
> 
> No more magical than metatables in general, in my opinion, but okay.

I'd just like to point out that you can (almost) get rid of numeric 
for-loops by hooking into the metatable for numbers today.

8<-------8<-------8<--------

-- Iterator function to make the syntax "for i in <limit>" and
-- "for i in <init>,<limit>" work in lua 5.1.  Doesn't support
-- a nonunit step.
function numeric_next(init, limit, var)
    if limit == nil then
        init, limit = 1, init
    end
    var = (var or init - 1) + 1
    if var <= limit then
        return var
    end
end

debug.setmetatable(123, { __call = numeric_next })

for i in 10 do print(i) end
-- prints 1,2,3,...,10

for i in 4,10 do print(i) end
-- prints 4,5,6,...,10