Lua读取文件异常及playerMonster数组元素重复问题求助
问题排查与解决方案
嘿,我一眼就瞅出你碰到的麻烦啦!你代码里的核心问题和Lua的表类型特性有关——你一直在把同一个表的引用塞进数组里,最后自然所有元素看起来全一样。
问题根源
你现在的monster表是在循环外面定义的对吧?Lua里的表是引用类型,它不像数值、字符串这类值类型会直接复制数据,而是存的内存地址指针。所以你每次循环修改的都是同一个monster表的内容,然后把它再次添加到playerMonster数组里——数组里的所有元素其实都是指向同一个内存对象的引用,最后显示出来当然全是最后一次修改的内容。
修复方案
最直接的解决办法就是把monster表的定义放到循环内部,让每次循环都创建一个全新的独立表:
local playerMonster = {} local function readfile() local path = system.pathForFile("playerpo.txt") local file = io.open(path, "r") if file then io.input(file) for i = 1, player.nummonster do -- 关键:每次循环新建一个独立的monster表 local monster = {no, power, def, speed, evade, hit, maxhp, spow, potype, lvevo, move1, mov2, smove, pmove, lv, numgame} -- 这里记得给当前monster的字段赋值对应的数据(比如从文件读取的内容) -- 示例:monster.no = io.read("*n") table.insert(playerMonster, monster) end io.close(file) end end
如果你需要复用一个基础的怪物表结构,也可以自己实现一个浅拷贝函数,每次循环拷贝一份再修改:
-- 浅拷贝函数,复制表的第一层内容 local function shallowCopy(t) local copy = {} for k, v in pairs(t) do copy[k] = v end return copy end local playerMonster = {} local function readfile() local path = system.pathForFile("playerpo.txt") local file = io.open(path, "r") -- 基础怪物结构(如果需要的话) local baseMonster = {no, power, def, speed, evade, hit, maxhp, spow, potype, lvevo, move1, mov2, smove, pmove, lv, numgame} if file then io.input(file) for i = 1, player.nummonster do -- 拷贝基础结构得到新表 local monster = shallowCopy(baseMonster) -- 给当前怪物设置独有的属性 -- 示例:monster.power = io.read("*n") table.insert(playerMonster, monster) end io.close(file) end end
额外提醒
别忘了在循环里给每个monster表的字段赋值对应的数据哦——比如从文件里读取当前怪物的编号、攻击力这些,不然就算表是新的,内容也会重复~
内容的提问来源于stack exchange,提问作者nguyen luan
相关产品推荐
相关产品推荐

