table的操作有疑问

HeroData = {} HeroData.nType  = 1 HeroData.strName  = "" HeroData.strInfo  = ""
local fileData = {}
local array = {}
HeroDataMgr = {}
function HeroDataMgr:loadData(  ) HeroData.nType = 1 HeroData.strName  = "TestPlayerName1" HeroData.srInfo = "TestPlayerInfo1" table.insert(fileData, HeroData) table.insert(array, HeroData.strName)
 HeroData.nType = 0 HeroData.nStrName  = "TestPlayerName2" HeroData.nStrInfo = "TestPlayerInfo2" table.insert(fileData, HeroData) table.insert(array, HeroData.strName)end
function HeroDataMgr:getData(nType) for i,value in ipairs(array) do print("getArray:"..i.."-value:"..value) end
 for i,value in ipairs(fileData) do print("getData:"..i.."-value:"..fileData.strName) if fileData.nType == nType then return value end end
 return nilend
return HeroDataMgr

如上代码,为何,第一个打印getArray获得的字符串是正常的,而第二个打印getData获得的字符串都是“TestPlayerName2”

代码是不是写错了


for i,value in ipairs(fileData) do 
    print("getData:"..i.."-value:"..fileData.strName) --这里的filedata 应该是value 吧 
     if fileData.nType == nType then return value end
end

因为你向 fileData 数组中插入的 HeroData 是同一个对象,也就是说其实fileData中的两个值,指向的是同一个引用

复制过来的代码打错了,谢谢了,我知道如何处理了