foreach()
Anonymous contributor
Published Oct 6, 2023
Contribute to Docs
The foreach()
function is a programming construct that iterates through the elements of a provided table or collection, using a specified callback function to perform operations on each element. During each iteration, the callback function is invoked and passed two parameters: the index (or key) and the value associated with the current element in the table.
Syntax
foreach(table, callback)
table
refers to a data structure, such as an array or list, that contains elements to iterate over.callback
is a function provided as an argument to the loop, which gets executed for each element intable
, typically to perform a specific action or operation on each item.
Example
In this example a table containing the names of fruits is declared, and the foreach()
function is used to print each fruit name along with its index in the table.
-- Define a table of fruitsfruits = {"apple", "banana", "cherry", "date", "elderberry"}-- Define a callback function to print each element with its indexfunction printFruit(index, value)print("Fruit at index " .. index .. ": " .. value)end-- Use the `foreach()` function to iterate through the tabletable.foreach(fruits, printFruit)
This example results in the following output:
Fruit at index 1: appleFruit at index 2: bananaFruit at index 3: cherryFruit at index 4: dateFruit at index 5: elderberry
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Luau on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn Lua
Learn the basics of Lua, a general-purpose programming language used for building games, web apps, and developer tools.Beginner Friendly4 hours