我是lua后端老师!
小仙,我来帮你优化这个函数。根据你的需求,我们需要用`getobjectinmap()`函数来获取指定类型的对象,并且不使用参数相加的方式。让我重新写一个更简洁的版本:
```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)
-- 定义类型映射表
local typeMap = {
[1] = 1, -- 玩家
[2] = 2, -- 怪物
[32] = 32, -- 人形怪
[64] = 64, -- 英雄
[128] = 128, -- 分身
[256] = 256 -- 宝宝、随从
}
-- 处理不填参数或参数为nil或空表的情况
if targetType == nil or (type(targetType) == "table" and #targetType == 0) 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) == "number" then
local flag = typeMap[targetType] or 0
if flag > 0 then
local objects = getobjectinmap(map_id, centerX, centerY, radius, flag)
if objects then
for _, obj in ipairs(objects) do
if obj then
table.insert(targets, obj)
end
end
end
end
return targets
end
-- 如果targetType是表,处理表中的对象类型
if type(targetType) == "table" then
for _, ttype in ipairs(targetType) do
local flag = typeMap[ttype] or 0
if flag > 0 then
local objects = getobjectinmap(map_id, centerX, centerY, radius, flag)
if objects then
for _, obj in ipairs(objects) do
if obj then
table.insert(targets, obj)
end
end
end
end
end
return targets
end
-- 其他情况返回空表
return {}
end
```
这个函数的主要改进:
1. **使用`getobjectinmap(map_id, centerX, centerY, radius, 0)`**来获取所有类型的对象,参数0表示获取全部
2. **建立类型映射表**,将你的参数映射到`getobjectinmap`的对应参数
3. **分三种情况处理**:
- 参数为nil或空表:获取所有对象
- 参数为单个数字:获取对应类型的对象
- 参数为表:遍历表,获取表中所有类型的对象
这样写更简洁,也符合你的需求。如果还有不明白的地方,随时问我哦!