Inside a for / pairs loop, I need to change the original element value of a dictionary:
MyDictionary = {Element1 = 1, OtherElement = 2, c = 3}
for i, v in pairs(MyDictionary) do
print(i, v) -- will print "Element1 1", "c 3", "OtherElement 2"
v = "x" -- will not change the original element value inside the dictionary
MyDictionary[i] = "x" -- this will change the value
end
If I have a complex/multilevel dictionary, the reference to change the element value will be more complex, as MyDictionary[level1][level2].Elementx[level3] = value
This is not user friendly.
Any way to change the original value only by reference? (as the example above, changing the variable v would change the MyDictionary[i] value…
No, there is no other way. You could make a feature request for this. But I think that tables inside tables are passed via reference, so you only have to index once. Not sure about that though.
I don’t think a feature request will work since it’s based on the Lua core…
It seems to not be correct:
local MyDictionary = {InnerDictionary = {a = "test1", b = "whatever"}}
for i, v in pairs(MyDictionary) do
for i, v in pairs(v) do
print(i, v)
v = "x" -- will not change the inner values
end
end
I was wrong. I indeed can change some inner element value by referencing, but in the correct way.
Here an example:
local MyDictionary = {}
MyDictionary.Param = 1
MyDictionary.Cell = {}
MyDictionary.Cell._001 = {}
MyDictionary.Cell._001.Materials = {}
table.insert(MyDictionary.Cell._001.Materials, {Material = "mat1", Distance = 123})
table.insert(MyDictionary.Cell._001.Materials, {Material = "mat2", Distance = 234})
MyDictionary.Cell._002 = {}
MyDictionary.Cell._002.Materials = {}
table.insert(MyDictionary.Cell._002.Materials, {Material = "mat3", Distance = 345})
table.insert(MyDictionary.Cell._002.Materials, {Material = "mat4", Distance = 456})
for cell, v in pairs(MyDictionary.Cell) do
print(cell)
for mat, v in pairs(v) do
print("\t", mat)
for i, v in ipairs(v) do
print("\t\t", i)
print(v.Distance)
v.Distance = 999 -- this WILL CHANGE the element value
for element, value in pairs(v) do
print("\t\t\t", element, value)
end
end
end
end
Output:
_001
Materials
1
123
Distance 999
Material mat1
2
234
Distance 999
Material mat2
_002
Materials
1
345
Distance 999
Material mat3
2
456
Distance 999
Material mat4