lua-users home
lua-l archive

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


Am 20.03.2016 um 11:47 schröbte rst256:
Sample code:

rules=setmetatable({x=5,66,y=9}, { __call=pairs })
     for k, v in rules do print(k, v) end

Output:
Infinite loop values k and v not changing, k == next and v==rules

Question:
This is normal, not bug?

Yes, this is normal.

Lua's for loop calls your table's `__call` metamethod (and as a result `pairs(rules)`) on every iteration.

What should work is

    rules = setmetatable( { x = 5, 66, y = 9 }, { __call = pairs } )
    for k,v in rules() do print( k, v ) end
    --              ^^

What you probably want is something like

    rules = setmetatable( { x = 5, 66, y = 9 }, {
      __call = function( st, _, var )
        return next( st, var )
      end
    } )

    for k,v in rules do print( k, v ) end

i.e. `rules` is called as an iterator, so it should behave like an iterator. `pairs` on the other hand is an iterator *generator* (it returns an iterator). You can't use `next` directly, because `__call` adds another argument (the table), and your for-loop doesn't specify the state variable that `next` expects (which would also be the table).

HTH,
Philipp