What is the difference of pairs() vs. ipairs() in Lua?

前端 未结 2 1843
孤城傲影
孤城傲影 2020-12-14 06:19

In a for loop, what is the difference between looping with pairs() and ipairs()? This page uses both: Lua Docs

With ipairs():

a = {\"one\", \"two\",          


        
2条回答
  •  太阳男子
    2020-12-14 06:49

    There is no array-type in Lua, only tables which might have consecutive elements starting from index 1.

    The generic for-loop, in contrast to the numeric for-loop, expects three values:

    1. A callable
    2. A context-value it passes on
    3. An initial index-value

    It calls the callable with context-value and index-value, storing all the returned values in the provided new variables. The first one is additionally saved as the new index-value.

    Now some representative examples of callables for the loop:

    1. ipairs(t) returns a function, the table t, and the starting-point 0.
      The function is the moral equivalent to:

      function ipairs_next(t, i)
          i = i + 1
          var v = t[i]
          if v ~= nil then
              return i, v
          end
      end
      

      Thus, all numeric entries starting at 1 until the first missing one are shown.

    2. pairs(t) either delegates to t's metatable, specifically to __pairs(t), or returns the function next, the table t, and the starting-point nil. next accepts a table and an index, and returns the next index and the associated value, if it exists.

      Thus, all elements are shown in some arbitrary order.

    3. There are no limits to how creative one can be with the function, and that is what vanilla Lua expects.
      See "Bizzare "attempt to call a table value" in Lua" for an example of a user-written callable, and how some dialects react if the first value is not actually a callable.

提交回复
热议问题