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.
Keys which have no value (ie: are
nil) do not exist.myTableis 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:
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:
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 throughmyTableor 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:
So it’s perfectly valid to modify the value of a field that already exists. And
keyobviously already exists in the table, so you can modify it. You can even set it tonilwith 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 ofmyTable[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.