Page 1 of 1

Gather all units of single type in a list?

Posted: Sun Dec 06, 2020 1:59 am
by aethertap
Hi all,

Just getting started with Lua scripting and CMO in general. I have experience with Python.

I'm wondering if there's a function or straightforward 'for' loop that will access all units on a side of type 'Surface Ship.' I have a scenario where I've placed a ton of random commercial merchant traffic and I'm looking to go through them and assign home bases and/or random headings. Obviously, the intent is to litter the area with random sea traffic, but I'm not sure that most straightforward way of automating this. Thanks!

RE: Gather all units of single type in a list?

Posted: Sun Dec 06, 2020 9:02 am
by boogabooga
Yes, that's difficult because generally you need to know a unit's name or guid ahead of time in order to GetUnit.

What I do, following others, is to create units directly in LUA and list them in a table as they are created in order to keep track of them. EX:
function AddFingerFour(callsign,side,dbid,loadout,latitudeIn,longitudeIn,heading,altitude,proficiency,groupName)
--local circle = World_GetCircleFromPoint({latitude=latitude,longitude=longitude,radius=0.5,numpoints = 72})
local addedAircraftTable = {}

blah blah blah

local unit = ScenEdit_AddUnit({type='Aircraft',side=side,dbid=dbid,name=callsign..' #'..i,loadoutid=loadout,latitude=position.latitude,longitude=position.longitude,heading=heading,altitude=altitude,proficiency=proficiency});
unit.group=groupName
table.insert(addedAircraftTable,unit)

return addedAircraftTable
end



Then the loop to access each unit:
for key, value in pairs(addedAircraftTable) do

blah blah blah

RE: Gather all units of single type in a list?

Posted: Sun Dec 06, 2020 11:24 am
by KnightHawk75
I'm wondering if there's a function or straightforward 'for' loop that will access all units on a side of type 'Surface Ship.' ...
---

Yes. Get the side wrapper, grab the unitlist by using unitsBy('Ship') method;

Code: Select all

local s = VP_GetSide({side="Red"});
 local tbl = s:unitsBy('Ship'); --All surface ships
 --local tbl2 = s:unitsBy('Ship','2002'); --example to further constrained to Surface Combatant
 --local tbl3 = s:unitsBy('Ship',nil,'2008'); --example to constrain to CVN sub-type's only
 local u; --unit wrapper
 local retval = false; --return value from pcall
 for k,v in pairs(tbl) do
   retval,u = pcall(ScenEdit_GetUnit,{guid=v.guid}); --suppress errors.
   if (retval == true) and u ~=nil then
      --Do Stuff You want with each unit.
      print(string.format("Unitname: %s  Lat: %s Lon: %s",tostring(u.name),tostring(u.latitude),tostring(u.longitude)));
      --
   else
     print('Could not obtain unit. err: ' .. tostring(u)); --u contains error msg if retval is false.
   end
   retval,u = false,nil;
 end