Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is actual implementation of lua __pairs?

Does anybody know actual implementation of lua 5.2. metamethod __pairs? In other words, how do I implement __pairs as a metamethod in a metatable so that it works exactly same with pairs()?

I need to override __pairs and want to skip some dummy variables that I add in a table.

like image 361
user2872907 Avatar asked May 13 '14 06:05

user2872907


People also ask

What are Lua pairs?

pairs(table) Lua provides a pairs() function to create the explist information for us to iterate over a table. The pairs() function will allow iteration over key-value pairs. Note that the order that items are returned is not defined, not even for indexed tables.

What is __ index in Lua?

The use of the __index metamethod for inheritance is so common that Lua provides a shortcut. Despite the name, the __index metamethod does not need to be a function: It can be a table, instead. When it is a function, Lua calls it with the table and the absent key as its arguments.

What is the difference between pairs and Ipairs?

The first difference between the pairs() and ipairs() function is that the pairs() function doesn't maintain the key order whereas the ipairs() function surely does.


1 Answers

The following would use the metatable meta to explicitly provide pairs default behavior:

function meta.__pairs(t)
  return next, t, nil
end

Now, for skipping specific elements, we must replace the returned next:

function meta.__pairs(t)
  return function(t, k)
    local v
    repeat
      k, v = next(t, k)
    until k == nil or theseok(t, k, v)
    return k, v
  end, t, nil
end

For reference: Lua 5.2 manual, pairs

like image 127
Deduplicator Avatar answered Sep 25 '22 17:09

Deduplicator