KnightHawk75
Posts: 1450
Joined: 11/15/2018 Status: offline
|
What is the code for a negative result? Here it would be == nil; But I'd recommend a pcall on SE_GetUnit and true\false check for success and then unit ~=nil check.
--sample list of units coded or generated on the fly, local var and function is just sample could be global just the same.
local somelist = {
[1]={side="B",name="Marauder #1"},
[2]={side="B",name="Marauder #2"},
[3]={side="B",name="Marauder #3"},
[4]={side="B",name="Marauder #4"},
[5]={side="B",name="Marauder #5"},
[6]={side="B",name="Marauder #6"},
[7]={side="B",name="Marauder #7"},
[8]={side="B",name="Marauder #8"}
}
-- takes in a table with name and side entries like the above^.
-- returns True if any of the units exists, false if none of them do, nil if there is an invalid parameter\bad table fed.
local function AnyUnitsExistByNameAndSide(listOfUnits)
if (listOfUnits ~=nil) and type(listOfUnits) ~= "table" then print("AnyUnitsExistByNameAndSide(): invalid paramter. aborting"); return; end
if (listOfUnits ==nil) then print("AnyUnitsExistByNameAndSide(): missing listofUnits paramter. aborting"); return; end
local retval,u;
for k,v in pairs(listOfUnits) do
retval,u = pcall(SE_GetUnit,{side=v.side,name=v.name}) --retval==true on successful getunit call, u is not nil when unit wrapper is obtained.
if(retval ==true) and u~=nil then return true; end -- if any of them are valid we can stop as we have our answer, no need to keep checking.
retval,u = false,nil;
end
return false; -- if we get this far none exist.
end
local function createUnitsAtBaseAssignMission(theside,thenameprefix,dbid,loadout,basename,missionname,amount)
local retval,u;
for i = 1, amount do
retval,u = pcall(ScenEdit_AddUnit,{type = 'Air', unitname = thenameprefix..i, loadoutid = loadout, dbid = dbid, side = theside, base=basename});
if (retval==true) and u ~= nil then
pcall(ScenEdit_AssignUnitToMission,u.guid,missionname); --assumes the mission name actually exists already.
end
end
end
--Sample Usage of the above
local doTheyAllExist=AnyUnitsExistByNameAndSide(somelist);
if (doTheyAllExist ~=nil) and doTheyAllExist==false then --we check we have valid return first, then if we do if it was false.
--call to code that recreates them since none exist.
print("none existed, recreating.");
createUnitsAtBaseAssignMission("B","Marauder",1404,5347,"B AIRBASE","Intercept",8)
else
print("At least one existed.");
end
< Message edited by KnightHawk75 -- 7/16/2021 11:50:30 PM >
|