"For each" loop in a lua table with key value pairs
Asked Answered
I

1

28

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.

Ironbound answered 26/10, 2012 at 6:4 Comment(0)
S
61

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.

Shorttempered answered 26/10, 2012 at 6:14 Comment(2)
I would add that modifying a table in the same loop that you are using to parse it with pairs is considered "undefined behavior" in Lua. It might work in one Lua implementation, but not on other. There are safer alternatives, like using an auxiliary table to note the changes and then parse it to apply them.Photothermic
@kikito: Not in this case. I've updated the post to explain.Shorttempered

© 2022 - 2024 — McMap. All rights reserved.