Page 1 of 1

Help Changing Code

Posted: Sun Feb 04, 2024 5:31 pm
by kahta
Hi,

I am looking to write a lua script to check if a unit is within 100nm of a unit with "comms" in the name of the unit.


My first script is not working and I keep getting a message related to the unit name not being a string.:

ERROR: [string "Console"]:11: bad argument #1 to 'find' (string expected, got nil)

Code: Select all

units = VP_GetSide({side='Honduras'}).units
print(units)

if(string.find(units.name, "Comm")) then
	local commcenter = VP_GetUnit ({guid=unit.guid})
	local units = VP_GetSide({side="Honduras"}).units
	for k,v in ipairs(units) do
		local dist = Tool_Range(v.guid,commcenter.guid)
			if dist > 75 then 
				ScenEdit_SetUnit({guid.v.guid,OutOfComms="True"})
            else
				ScenEdut_SetUnit({guid.v.guid,OutOfComms="False"})
            end
    end
end


My second script (based on something I found on the forums) is working.

Code: Select all

function isincomms(unit)
  local comm_units ={
  {name='Hond Comms', guid='CNJF8E-0HN15GS7IG0HO'},
  {name='Hond Comms', guid='CNJF8E-0HN15GS7IG124'},
  {name='Hond Comms', guid='CNJF8E-0HN15GS7IG128'},
  {name='Hond Comms', guid='CNJF8E-0HN15GS7IM3UA'},
  {name='Hond Comms', guid='CNJF8E-0HN15GS7IM3KQ'},
  {name='Hond Comms', guid='CNJF8E-0HN15GS7IG13O'}
 
  }
  for _,comm in ipairs(comm_units) do
    if Tool_Range(unit.guid,comm.guid) <= 100 then
      return true
    end
  end
  return false
end

local units = VP_GetSide({side='Honduras'}).units
for _,v in ipairs(units) do
  local unit = SE_GetUnit({guid = v.guid})
  if isincomms(unit) then
    ScenEdit_SetUnit({guid=unit.guid,outofcomms=false})
  else
    ScenEdit_SetUnit({guid=unit.guid,outofcomms=true})
  end
end

Re: Help Changing Code

Posted: Mon Feb 05, 2024 10:56 am
by lumiere
Insert for k, v in pairs(units) loop before string.find so that script can crawl the units table and check each of name value.

Code: Select all

for k, v in pairs(units) do
  if(string.find(v.name, "Comm")) then
    --do something 
  end
end

Re: Help Changing Code

Posted: Mon Feb 05, 2024 8:35 pm
by kahta
lumiere wrote: Mon Feb 05, 2024 10:56 am Insert for k, v in pairs(units) loop before string.find so that script can crawl the units table and check each of name value.

Code: Select all

for k, v in pairs(units) do
  if(string.find(v.name, "Comm")) then
    --do something 
  end
end
Thanks!

Next question... Would it be hard to add a second level of variability in this so that if the comms unit was aircraft it would be a different range than if it was a building?

Re: Help Changing Code

Posted: Tue Feb 06, 2024 7:26 am
by blu3s
Retrieve the unit wrapper using SE_GetUnit() and use unit.type to check the type

Re: Help Changing Code

Posted: Tue Feb 06, 2024 5:11 pm
by kahta
Great, thanks again!