LUA Increment Unit Name

All discussions & material related to Command's Lua interface

Moderators: RoryAndersonCDT, michaelm75au, angster, MOD_Command

Post Reply
Relayer2112
Posts: 8
Joined: Sat Dec 28, 2013 8:24 pm

LUA Increment Unit Name

Post by Relayer2112 »

Hi folks,

I'm getting to grips with using LUA for pretty much the first time. I'm using it to build a scenario which uses special actions to 'buy' units at a points cost, in a manner similar to the old Sultan of Socotra scenario. The issue I'm running into is with incrementing the names of units.

It's easy enough for me to generate incremented names when creating units using a loop:
eg -

Code: Select all

for loop = 1, 4, 1 do
 	ScenEdit_AddUnit({type = 'Air', unitname = 'Fulcrum #'..loop, loadoutid = 26807, dbid = 740, side = 'REDFOR', base = 'Tonopah Test Range Airport'})
 end
 

But, for creating the Blue units, it's not quite so simple because I don't want to lock the player into generating whole groups - I want the player to 'buy' each unit individually. This is the script I'm currently using to do so:

Code: Select all

ScenEdit_AddUnit({type = 'Air', unitname = 'Falcon #', dbid = 158, loadoutid = 3, side = 'BLUFOR', base = 'Nellis AFB'})
 local score = ScenEdit_GetScore('BLUFOR')
 score = score - 100
 ScenEdit_SetScore('BLUFOR', score, 'F-16A Added to Nellis AFB')

But of course, if I trigger this event 4 times, I end up with 4 units called 'Falcon #' rather than 'Falcon #1-4'. Do I need to find some way of checking for the existence of a unit with the name 'Falcon #1' and somehow incrementing it to 'Falcon #2'?

There probably is an elegant, straightforward way of doing this but I'm only currently getting to grips with the language! Many thanks in advance.
User avatar
michaelm75au
Posts: 12464
Joined: Sat May 05, 2001 8:00 am
Location: Melbourne, Australia

RE: LUA Increment Unit Name

Post by michaelm75au »

You want to uniquely name the units so you need some sort of counter
...
ScenEdit_AddUnit({type = 'Air', unitname = 'Falcon #' .. counter, dbid = 158, loadoutid = 3, side = 'BLUFOR', base = 'Nellis AFB'})
counter = counter +1
....

The counter could be a global Lua variable but that will get reset when you start Command. A better idea would be to keep the counter in the KeyStore that retained between saves.
ScenEdit_SetKeyValue("UnitId","2")
ScenEdit_GetKeyValue("UnitId") -- returns "2"

As for if unit exists, use this in a script and it will return nil if the unit doesn't exist.
ScenEdit_GetUnit({unitname = 'Falcon #1', side = 'BLUFOR'})
Michael
Post Reply

Return to “Lua Legion”