Say I have a table defined like this:
myTable = { myValue = nil, myOtherValue = nil}
How would I iterate through it in a for each fashion loop like this?
for key,value in myTable do --pseudocode value = "foobar" end
Also, if it helps, I don't really care about the key, just the value.
For tables using numeric keys, Lua provides an ipairs function. The ipairs function will always iterate from table[1] , table[2] , etc. until the first nil value is found. A final way to iterate over tables is to use the next selector in a generic for loop.
LuaServer Side ProgrammingProgramming. In Lua, we make use of both the pairs() and ipairs() function when we want to iterate over a given table with the for loop. Both these functions return key-value pairs where the key is the index of the element and the value is the element stored at that index table.
In Lua, there are 3 basic types of loops. They are while, for, and repeat. While loops repeat as long as a variable is the boolean "true." If you create a variable with a value other than false or nil, it is true.
Keys which have no value (ie: are nil
) do not exist. myTable
is an empty table as far as Lua is concerned.
You can iterate through an empty table, but that's not going to be useful.
Furthermore:
for key,value in myTable do --pseudocode value = "foobar" end
This "pseudocode" makes no sense. You cannot modify a table by modifying the contents of a local variable; Lua doesn't work that way. You cannot get a reference to a table entry; you can only get a value from the table.
If you want to modify the contents of a table, you have to actually modify the table. For example:
for key,value in pairs(myTable) do --actualcode myTable[key] = "foobar" end
Notice the use of myTable
. You can't modify a table without using the table itself at some point. Whether it's the table as accessed through myTable
or via some other variable you store a reference to the table in.
In general, modifying a table while it iterating through it can cause problems. However, Lua says:
The behavior of
next
is undefined if, during the traversal, you assign any value to a non-existent field in the table. You may however modify existing fields. In particular, you may clear existing fields.
So it's perfectly valid to modify the value of a field that already exists. And key
obviously already exists in the table, so you can modify it. You can even set it to nil
with no problems.
Variables in Lua are nothing more than holders for values. Tables contain values; myTable[key]
returns a value. You can store that value in a variable, but changing the variable will not change the value of myTable[key]
. Since tables are stored by reference, you could change the contents of the table in one variable and see the changes in another, but that is simply the contents of the table, not the table itself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With