local equipInfo = {}
local num = 0
for k, v in ipairs(EquipPos) do
num = num + 1
local Equip_k = linkbodyitem(actor, k)
if Equip_k then
local eqName = getiteminfo(actor, Equip_k, 7)
local eq
嗨!我是Lua后端老师!
修仙者,你遇到的问题是因为`ipairs`遍历方式导致的。让我详细解释一下:
**问题分析:**
你的`EquipPos`表使用了非连续数字作为键(0,1,2,3,4,5,6,7,8,10,11),而`ipairs`只能遍历连续数字索引的数组部分(从1开始的连续整数序列)。
`ipairs`的工作方式是从索引1开始,依次访问1,2,3...直到遇到`nil`为止。你的表中:
- 索引1-8是连续的(对应装备位置1-8)
- 但索引9不存在(因为你有0-8,然后直接跳到10)
- 所以`ipairs`遍历到索引8后就停止了
**解决方案:**
使用`pairs`代替`ipairs`来遍历所有键值对:
```lua
local equipInfo = {}
local num = 0
for k, v in pairs(EquipPos) do -- 将 ipairs 改为 pairs
num = num + 1
local Equip_k = linkbodyitem(actor, k)
if Equip_k then
local eqName = getiteminfo(actor, Equip_k, 7)
local eqIdx_k = getiteminfo(actor, Equip_k, 2)
if not eqName then
eqName = "未装备"..v
end
equipInfo[num] = {
name = eqName,
idx = eqIdx_k,
pos = k
}
else
-- 如果装备不存在
equipInfo[num] = {
name = "未装备"..v,
idx = 0,
pos = k
}
end
end
local itemObj = linkbodyitem(actor, param3)
release_print(equipInfo) -- 使用 release_print 替代 dump
```
**两种遍历方式的区别:**
- `ipairs`: 只遍历连续数字索引(1,2,3...),遇到`nil`就停止
- `pairs`: 遍历表中的所有键值对,包括非连续数字、字符串等键
**额外建议:**
如果你希望按照装备位置的顺序(0,1,2,3...)来存储,可以这样调整:
```lua
local equipInfo = {}
for pos, name in pairs(EquipPos) do
local Equip_k = linkbodyitem(actor, pos)
if Equip_k then
local eqName = getiteminfo(actor, Equip_k, 7)
local eqIdx_k = getiteminfo(actor, Equip_k, 2)
if not eqName then
eqName = "未装备"..name
end
equipInfo[pos] = { -- 使用pos作为索引,保持顺序
name = eqName,
idx = eqIdx_k,
pos = pos
}
else
equipInfo[pos] = {
name = "未装备"..name,
idx = 0,
pos = pos
}
end
end
```
这样修改后,你的`equipInfo`表就会包含所有装备位置(0-11)的信息了。如果还有其他不明白的地方,随时问我哦!