嗨,修仙者!我是Lua后端老师!
看到你的代码了,你想优化这个函数,让它能处理更多参数情况,特别是当不填参数时获取所有类型,以及处理空表`{}`的情况。我来帮你调整一下。
```lua
function godTier_skill_trigger:GetTargetsInRange(actor, centerX, centerY, radius, targetType)
release_print("GetTargetsInRange", centerX, centerY, radius, targetType)
local targets = {}
local map_id = getbaseinfo(actor, 3)
-- 处理targetType参数为空或nil的情况
if targetType == nil or targetType == "" then
-- 获取所有类型对象
local allObjects = getobjectinmap(map_id, centerX, centerY, radius, 0) -- 0表示获取所有类型
if allObjects then
for _, obj in ipairs(allObjects) do
if obj then
table.insert(targets, obj)
end
end
end
return targets
end
-- 如果targetType是表,处理表中的对象类型
if type(targetType) == "table" then
-- 处理空表的情况
if #targetType == 0 then
-- 空表也按获取所有类型处理
local allObjects = getobjectinmap(map_id, centerX, centerY, radius, 0)
if allObjects then
for _, obj in ipairs(allObjects) do
if obj then
table.insert(targets, obj)
end
end
end
return targets
end
local getPlayers = false
local getMonsters = false
local getHeroes = false
local getCopies = false
-- 遍历表,设置要获取的类型标志
for _, ttype in ipairs(targetType) do
if ttype == 1 then
getPlayers = true
elseif ttype == 2 then
getMonsters = true
elseif ttype == 4 or ttype == 64 then
getHeroes = true
elseif ttype == 8 or ttype == 128 then
getCopies = true
end
end
-- 根据标志获取对应类型的对象
if getPlayers or getHeroes or getCopies then
local flag = 0
if getHeroes and getCopies then
flag = 64 + 128 -- 同时获取英雄和分身
elseif getHeroes then
flag = 64 -- 只获取英雄
elseif getCopies then
flag = 128 -- 只获取分身
end
local objects = getobjectinmap(map_id, centerX, centerY, radius, flag)
if objects then
for _, obj in ipairs(objects) do
if obj then
if getHeroes and ishero(obj) then
table.insert(targets, obj)
elseif getCopies and isplayer(obj) and getbaseinfo(obj, 1) ~= actor then
table.insert(targets, obj)
elseif getPlayers and isplayer(obj) then
table.insert(targets, obj)
end
end
end
end
end
-- 获取怪物(包括宝宝)
if getMonsters then
local monsters = getobjectinmap(map_id, centerX, centerY, radius, 2) -- 2表示获取怪物
if monsters then
for _, monster in ipairs(monsters) do
if monster and ismon(monster) then
local master = getbaseinfo(monster, 67) -- 获取怪物主人
-- 如果是宝宝(有主人)或者普通怪物
if (master and master ~= "") or not master then
table.insert(targets, monster)
end
end
end
end
end
return targets
end
-- 如果targetType不是表也不是nil,返回空表
return {}
end
```
主要修改点:
1. 增加了对`targetType`参数为`nil`或空字符串的处理,这种情况下获取所有类型对象
2. 增加了对空表`{}`的处理,也按获取所有类型对象处理
3. 在函数末尾添加了对非表、非空参数的处理,返回空表
这样你的函数就能处理更多情况了:
- 不传`targetType`参数:获取所有类型
- 传空表`{}`:获取所有类型
- 传具体的类型表:按表内类型获取
如果还有其他问题,随时问我!