Lua Logo
The generic for

We are able to read out a numerical table like

myTable[number] with a regular for-loop.

However, with such a kind of loop we would not succedd in reading out tables like:

myTable.myName

But this is exactly the ability of the generic for - loop.

for variable, value in pairs(table) do -- since Lua 5.1 the function pairs has to be used
-- chunck
end

Note:
The function pairs(table) returns the function next followed by the table.
We would also be able to write:

for variable, value in next,table do
-- chunck
end

Regardless if we have a numerical table or a table with names, this generic for-loop traverse every value of the table.

Example: We create a table with every week day

days = {"Sunday", "Monday", "Tuesday","Wednesday",
"Thursday", "Friday", "Saturday"}

Now we have a table as follows:

days[1] = "Sunday"
days[2] = "Monday"
days[3] = "Tuesday"
days[4] = "Wednesday"
days[5] = "Thursday"
days[6] = "Friday"
days[7] = "Saturday"

days is a numerical table

Now it's time for our generic loop. We do not have to know the table size as every value will be traversed until we get a nil-value.

numberforDay = {} -- new table
for variable, value in pairs(days) do
numberforDay[value] = variable
end


Explanation:

  • we create an empty table (numberforDay)
  • the loop traverse every value of the table days
  • in every cycle the variable (called variable in our example) gets the value which is addressed. In our case these are the numbers [1...7]
  • in every cycle the variable (called value in our example) gets the value of the according number [Sunday ... Saturday]
  • finally the chunck creates a new part of the table numberforDay like as follows:

numberforDay.Sunday = 1

.....

numberforDay.Saturday = 7



Now we are going to check this in the editor (because we also want to see what we have read)

for generisch

Due to the loop:

for i,v in pairs(days) do
numberforDay[v] = i
end

we also see, that there exists another kind of creating a table with names

numberforDay.Sunday = 1 -- we already know
numberforDay["Sunday"] = 1 -- we have just learned
numberforDay = {Sunday = 1} -- is possible as well



Do you also agree that this is really versatile? We only need to use it according our demand.
Copying of any content of this site (text or graphics) is not allowed, excepted any source code shown in this tutorial. See also: ....Disclaimer
Copyright © Robert Schmitz 2006