1

Just saw this in the Lua self examples...

  -- Example 24   -- Printing tables.
  -- Simple way to print tables.

  a={1,2,3,4,"five","elephant", "mouse"}

  for i,v in pairs(a) do print(i,v) end


  -------- Output ------

  1       1
  2       2
  3       3
  4       4
  5       five
  6       elephant
  7       mouse

  Press 'Enter' key for next example

I haven't seen this syntax before, for i,v in pairs(a) do print(i,v) end

Where did the v come into existence ?

Does the word in cause it to exist ?

By the same token, where does the i come into existence ?

Is this a syntax designed for tables ?

Thanks for any explanation.

1

1 Answer 1

3

pairs returns an iterator over all fields and their values

more exactly it's a function of table and previous seen index which returns pair of index and its value.

> t = {4,5,6}
> p = pairs(t)
> =p(t)
1   4
> =p(t,1)
2   5
> =p(t,2)
3   6

there are 2 options: iterate over every keys or just those which are integers: pairs and ipairs functions

this loop is very similar to python's

l = [4,5,6]
for i, v in enumerate(l):
    ...

or

d = {"a":1, "b":2}
for k, v in d.iteritems():
    ...

if you know python (it looks like everyone knows it)

Sign up to request clarification or add additional context in comments.

1 Comment

To prevent confusion: ipairs doesn't iterate over all keys that are integers; It iterates from 1 to n-1, where n is the index of the first nil value encountered.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.