Turned Based Fighting Help

Provide an overview of:

  • What does the code do and what are you not satisfied with?: If a unit has 2x more speed than another opponent, they can attack twice. Problem is I can’t think of a way for it to work for 3x, 4x, and so on.
  • What potential improvements have you considered?: I thought of doing the same process for 3x and 4x, however I think it would overlap and I can’t think of a way of placement.
  • How (specifically) do you want to improve the code?: As mentioned above^
-- [[ Making the Attack Sequence ]] --
	local speedTable = {}
	local finalTable = {}
	for _, UnitData in BattleTable do
		table.insert(speedTable, {ID = UnitData.ID, Speed = UnitData.Stats.Speed})
		table.sort(speedTable, function(Unit1,Unit2)
			return Unit1.Speed > Unit2.Speed
		end)
	end
	-- [[ Duplicate Faster Units ]] --
	
	-- Duplicate a unit in speedtable if speed is twice higher than another unit's speed
	for _, UnitData in speedTable do
		print(UnitData)

		-- do another for loop to check if speed is twice as fast as another unit's speed
		for i, UnitData2 in speedTable do
			-- if it is, duplicate it in the speedtable
			if UnitData.Speed >= UnitData2.Speed*2 then
				-- insert into the middle of the table right before this current unit
				print("Found Double Speed!", i)
				table.move(speedTable, 1, i-1, 1, finalTable)
				table.insert(finalTable, {ID = UnitData.ID, Speed = UnitData.Speed})
				table.move(speedTable, i, #speedTable, #finalTable+1, finalTable)
				break
			end
		end
		
	end

I can provide more information if needed! Thank you!

I could not understand how this game logic works exactly but if it’s turn based instead of this solution you can implement a queue system which will process 1 attack at a time. Then you can implement a basic data structure for attack counts (instead of speeds) which the game will process one by one until it gets to 0.

{
 {
   Name = "Unit 1",
   Attacks = 3,
 },
 {
  Name = "Unit 2",
  Attacks = 1,
 },
--proceed with the next player/npc
}

Looping this with ipairs will guarantee the order. As I said I don’t know if this is what you wanted but at least it should help a bit if not.