0

What is the purpose of Line 2 In my code?

local table = {["First"] = 1, ["Second"] = 2, ["Third"] = 3}

for key, value in pairs(table) do
    print(key)
end

Results-------------

First
Second
Third

What is the purpose of the line that says, "for key, value in pairs(table) do Print(key) ? I was wondering why it is essential.

4
  • 4
    Start reading "Programming in Lua" - best tutorial on Lua Commented Feb 4, 2019 at 18:23
  • ... the first edition of which is even available online for free! lua.org/pil/contents.html Commented Feb 5, 2019 at 2:42
  • 1
    Actually, line 2 is an empty one. Commented Feb 5, 2019 at 8:38
  • Array is a foreign concept in Lua. A Lua table is a dictionary in computer science terms. The Lua Reference Manual is a good place to learn, too. Commented Feb 5, 2019 at 11:27

1 Answer 1

3

As others have suggested in comments, you should really start by reading Programming in Lua. It will explain this and much more and is really a perfect place to start if you want to learn Lua.

Well then, as for what it does

Given a table like this

local tab = {first = 1, second = 2, third = 3}

the way you would usually iterate over all the key-value pairs in the table is like this

for key, value in pairs(tab) do
  print(key .. ": " .. tostring(value))
end

This will loop over the three values in the table first = 1, second = 2, etc. For each pair, key is set to the table key and value to its value. It then executes the code between do and end with those variables set.

So the example above will print the following:

first: 1
second: 2
third: 3

How does it work?

This is a bit more complex; Let's first of all see what pairs actually returns:

> t = {}
> print(pairs(t))
function: 68f18400    table: 0066b1d8    nil

The table it returns as its second argument is the same that we passed in.

The function that's returned by pairs is the next function, which, given a table and a key, returns the next key in the table, within an unknown order but without ever repeating keys.

You can easily confirm that on the command line.

> print(t)
table: 0066b1d8
> print(next)
function: 68f18400

Lua then turns the for loop into something like the following:

do
  local f, state, iterator = next, tab, nil -- this is what's returned by pairs
  while true do
    local key, value = f(state, iterator)
    if key == nil then break end
    iterator = key
    print(key, value) -- This is the body of our for loop
  end
end
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Dark, I appreciate your time for helping me out :)

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.