我认为运行这段代码你会得到我的意思。我想在注册表中注册5个名字(人)。我循环了5次,在每个循环中我有一个变量 newPerson ,它应该保存有关一个人的所有信息,然后被添加到 people 寄存器中。在此示例中,为简单起见,仅注册人员的姓名。 问题是,最终所有人都变成了同名:“佩特拉”。我对此有点玩,但无法得到这种行为的合理理由。帮助赞赏!
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"])
答案 0 :(得分:5)
这里最重要的是Lua变量“包含”一个表实际上只包含对表的引用。复制包含表的变量只会将引用复制到该表,因此表示与此示例中相同的表:
a={"x","y","z"}
b=a
b[2]="Q"
print(a[2]) -- returns Q and not y. Why is easily seen by doing:
print(a,b) -- returns table: 0xXXXXXX 0xXXXXXX indicating it's the same table
如果你真的想要一份表格副本,你需要求助于http://lua-users.org/wiki/CopyTable
答案 1 :(得分:2)
试试这个:
local people={}
local names={"Markus", "Eva", "Nikol", "Adam", "Petra"} --people to register
for i=1, 5 do
people[i]={
name=names[i],
lastName="Seferidis",
class="B"
}
end
答案 2 :(得分:1)
您似乎正在尝试将person
用作prototype object。以下是对代码的一些更改,这些更改添加了new
函数以便于对象原型设计。
object = {}
function object:new(o)
-- use the table provided, or create a new table
o = o or {}
-- use this object as a prototype
setmetatable(o, self)
self.__index = self
return o
end
local people={}
local person=object:new({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:new({["name"]=names[i]})
people[i]=newPerson
end
print("First person name: " ..people[1].name.." "..people[1].lastName.." "..people[1].class)
-->First person name: Markus Seferidis B
print("Second person name: "..people[2].name.." "..people[2].lastName.." "..people[2].class)
-->Second person name: Eva Seferidis B
print("Third person name: " ..people[3].name.." "..people[3].lastName.." "..people[3].class)
-->Third person name: Nikol Seferidis B