Lua: Why changing value on one variable changes value on an other one too?
- by user474563
I think that running this code you will get excactly what I mean. I want to register 5 names to a register(people). I loop 5 times and in each loop I have a variable newPerson which is supposed to save all information about a person and then be added to the people register. In this example only the names of the people are being registered for simplicity.
The problem is that in the end all people turn to have the same name: "Petra". I playied a bit with this but can't get a reasonable reason for this behaviour. Help appreciated!
local people={}
local person={
name="Johan",
lastName="Seferidis",
class="B"
}
local names={"Markus", "Eva", "Nikol", "Adam", "Petra"} --people to register
for i=1, 5 do --register 5 people
local newPerson=person
local name=names[i]
for field=1, 3 do --for each field(name, lastname, class)
if field==1 then newPerson["name"]=name end --register name
end
people[i]=newPerson
end
print("First person name: " ..people[1]["name"])
print("Second person name: "..people[2]["name"])
print("Third person name: " ..people[3]["name"])