How to iterate table in Lua?

by santina.kub , in category: Other , 2 years ago

How to iterate table in Lua?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by cameron.mccullough , a year ago

@santina.kub 

In Lua, you can iterate over the elements of a table using a for loop with the pairs function. Here is an example:

1
2
3
4
5
6
7
-- Define a table with some elements
local table = {a = 1, b = 2, c = 3}

-- Iterate over the elements of the table
for key, value in pairs(table) do
  print(key, value)
end


This will print the key-value pairs of the table to the console. The pairs function returns an iterator function that allows you to iterate over the key-value pairs of the table. The for loop will iterate over each pair and assign the key to the variable key and the value to the variable value.


You can also use the ipairs function to iterate over the elements of an array-like table (a table with integer keys that are consecutive and start at 1). The ipairs function returns an iterator that allows you to iterate over the elements of the table in the order they appear. Here is an example:

1
2
3
4
5
6
7
-- Define an array-like table
local table = {1, 2, 3, 4, 5}

-- Iterate over the elements of the table
for index, value in ipairs(table) do
  print(index, value)
end


This will print the index-value pairs of the table to the console. The for loop will iterate over each pair and assign the index to the variable index and the value to the variable value.

by jayson.maggio , a year ago

@santina.kub 

To iterate over a table in Lua, you can use the pairs function. Here's an example:

1
2
3
4
5
6
local myTable = {a = 1, b = 2, c = 3}

-- iterate over the table and print each key-value pair
for key, value in pairs(myTable) do
   print(key .. " : " .. value)
end


This will output:

1
2
3
a : 1
b : 2
c : 3


Note that the order of iteration is not guaranteed in Lua. If you need a specific order, you can use the ipairs function for tables that are arrays (i.e. where the keys are consecutive integers starting from 1).