Invalid argument #2 to 'random' (interval is empty)

Im making a boss fight type of game and i want to randomize the boss attacks im planning to put all the attacks to a table then let the math.random choose the index for the attack

tried to search for this "invalid argument #2 to ‘random’ (interval is empty) " error which is the title of this topic

heres my code if you want further knowledge on what did i do wrong




local attacks = {




	meteor = function()
		
		
		local amount = 30
		local function MeteorFall()
			task.spawn(function()
				local randomPos = Vector3.new(math.random((workspace.range.Position.X - workspace.range.Size.X/2),(workspace.range.Position.X + workspace.range.Size.X/2)),-639.896,math.random((workspace.range.Position.Z - workspace.range.Size.Z/2),(workspace.range.Position.Z + workspace.range.Size.Z/2)))
				local meteor = game.ReplicatedStorage.Meteor:Clone()
				meteor.Position = randomPos + Vector3.new(0,100,0)
				meteor.Parent = workspace

				wait(4)
				meteor:Destroy()


			end)
		end
		
		
		for i=1, amount do
			
			MeteorFall()
			wait(0.6)
		end

	end,



	hand = function()
		for i,v in pairs(workspace.Players:GetChildren()) do
			local hand = game.ReplicatedStorage.HandMesh:Clone()
			hand.AlignPosition.Attachment1 = v.Head.HatAttachment
			hand.Parent = workspace
			wait(5)
			hand:Destroy()
		end		
	end,	


	caged = function ()
		for i,v in pairs(workspace.Players:GetChildren()) do
			local num = math.random(1,#workspace.Players:GetChildren())
			if num == i then
				local cage = game.ReplicatedStorage.Cage:Clone()
				task.spawn(function()
					cage.Parent = workspace
					cage.Position = v.HumanoidRootPart.Position
					wait(10)
					cage:Destroy()
				end)
				
				
				break
				
			end
		end
	end
}


while workspace.bosshead.Humanoid.Health ~= 0 do
	
	for i,v in pairs(attacks) do
		print("yes")
		local randomattack = math.random(1,#attacks)
		return attacks[randomattack]
		
	end
	task.wait(3)
end
	

image

Which line is throwing out the error?

local randomattack = math.random(1,#attacks)

Maybe try putting the functions in (), like caged = (function() - - code end) and then run the code again

Hi. We know the fact that the first argument is 1; the second argument should be equal to or larger than the other one. The error implies that the passed argument is smaller than 1; otherwise it could flawlessly run.

The hash symbol is not the solution to getting the number of alphabetic keys in the table. Therefore that’s why #attacks is 0. Start a local function at the beginning of the script; you can retrieve that info with it.

local function count(tab)
    local c = 0

    for _, v in tab do
        c += 1
    end

    return c
end

Safely replace #attacks with count(attacks)

Hopefully helps!

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.