-- 获取武器主属性attid的函数
-- @param actor 玩家对象
-- @param itemobj 物品对象(武器)
-- @return 主属性attid(2=攻击,3=魔法,4=道术,0=无主属性或非武器)
local function getWeaponMainAttId(actor, itemobj)
-- 获取武器的基础攻击、魔法、道术属性值
local dcValue = getitemattidvalue(actor, 1, 2, -2, itemo
🤖 回答引擎: 后端Lua |
🕒 时间: 2026-05-21 10:33:14 |
👁️ 阅读: 0
我是lua后端老师!
小仙,你这个函数写得不错,逻辑清晰!不过确实可以简化一下,让代码更紧凑。
简化思路是:
1. 用表来存储属性ID和对应的值
2. 用一次循环找出最大值
3. 直接返回对应的属性ID
```lua
-- 获取武器主属性attid的函数(简化版)
-- @param actor 玩家对象
-- @param itemobj 物品对象(武器)
-- @return 主属性attid(2=攻击,3=魔法,4=道术,0=无主属性或非武器)
local function getWeaponMainAttId(actor, itemobj)
local atts = {
[2] = getitemattidvalue(actor, 1, 2, -2, itemobj), -- 攻击
[3] = getitemattidvalue(actor, 1, 3, -2, itemobj), -- 魔法
[4] = getitemattidvalue(actor, 1, 4, -2, itemobj) -- 道术
}
local maxId, maxValue = 0, 0
for id, value in pairs(atts) do
if value > maxValue then
maxId, maxValue = id, value
end
end
return maxId
end
```
这样改的好处是:
1. 代码行数减少了
2. 逻辑更集中,便于维护
3. 如果要增加其他属性判断(比如神圣、刺术等),只需要在`atts`表里加一行
不过要注意,如果两个属性值相同且都是最大值,这个函数会返回后遍历到的那个。
如果你需要更精确的处理(比如属性值相等时返回0),可以在循环后加个判断。
你觉得这个简化版本怎么样?
← 返回问答库