How do I choose random numbers from a table?

Hello! I have a part spawner that spawns parts very second and I want some parts to damage the player. The damage is chosen from a table of numbers and when the part is touched, the player is damaged. The problem is, it doesn’t work.
Here is my code:

local part = script.Parent

part.BrickColor = BrickColor.random()

local damageTable = {
		0,
		1,
		10,
		50,
		100
}

local function onTouched(hit)
	local Player = game.Players:GetPlayerFromCharacter(hit.Parent)
	if not Player then return end
	local Character = Player.Character or Player.CharacterAdded:Wait()
	local humanoid = Player.Character:WaitForChild("Humanoid")
	
	local leaderstats = Player:WaitForChild("leaderstats")
	leaderstats.Parts.Value += 1
	part:Destroy()
	
	local damageTaken = math.random(#damageTable, 1)
	humanoid:TakeDamage(damageTaken)
end

part.Touched:Connect(onTouched)

If you think you know what went wrong, please let me know. Thank you and have a great day!

5 Likes
  1. Why don’t you just generate a random number from 1-100 for the damage? To do this you can simply do Random.new():NextNumber(1, 100)

  2. To fix your problem, you can try damageTable[math.random(1, #damageTable)] which will REFRENCE the random object in your table.

7 Likes

The first argument x is the minimum amount the number should go, which should be 1, as lua’s table index starts at 1, while the second parameter y is the maximum it can go, which should be the total number of items in your table, aka #damageTable.
However, you can just only apply a single paramater to use, which should be the exact same, like this:

math.random(#damageTable) -- equivilent to math.random(1, y)

When trying to pick a item in an Array, you need an index, which is the key assigned to a value in the table, for example if I have this table {"Apple", "Orange"}, Apple will automatically have the index 1 assigned to it, and Orange will have the index 2, in order to access these values, it will need the index, when we have the index, we specify our table, and then add brackets [] with a number to specify our index. If we wanted to pick orange, i would have to say t[2], t being our table, and 2 being our index to access so called Orange.

However with Dictionaries, this wont work, as we have specified names on our values, and they arent counted for when we try to count them using the # operator, for example:

Cart = {
    Apple = 1,
    Orange = 3,
}
-- Apple and Orange now specify a value here, and they each hold a specific
-- value, in order to access them, we need to specify a string, instead of a
-- number, like the following:


Cart.Apple
Cart["Apple"]
6 Likes

I can do this:

local damageTaken = Random.new():NextNumber(1, 100)
humanoid:TakeDamage(damageTaken)

or this:

local damageTaken = damageTable[math.random(#damageTable)]
humanoid:TakeDamage(damageTaken)

Did I understand you right?

4 Likes

Yeah, you understood, BUT this will error

You need to put math.random(1, #damageTable) so it knows how many items there are possible. The Random.new method will generate a random number from 1 - 100 with decimals included.

3 Likes

Like this?

local damageTaken = math.random(1, #damageTable)
3 Likes

no, like this

local damageTaken = damageTable[math.random(1, #damageTable)]
2 Likes

I copy and pasted it into my code, but it doesn’t work.

3 Likes

why not just generate a random number?

1 Like

Using the Random.new() function?

1 Like

To choose random numbers from a table in Roblox Lua, you can use the math.random function along with the length of the table to generate a random index for the table. Here’s how you can do it:

luaCopy code

-- Define your table of numbers
local numberTable = {10, 20, 30, 40, 50, 60, 70}

-- Function to get a random number from the table
local function getRandomNumberFromTable()
    local randomIndex = math.random(1, #numberTable) -- Generate a random index
    return numberTable[randomIndex]
end

-- Call the function to get a random number
local randomNum = getRandomNumberFromTable()
print("Random number:", randomNum)

In this example, the math.random function generates a random integer between the specified range (1 and the length of the table). This random index is then used to access a number from the table.

If you want to select multiple random numbers from the table without repeating, you can use a shuffling algorithm to shuffle the table and then iterate through the shuffled table to get your random numbers. Here’s a simplified example:

luaCopy code

-- Define your table of numbers
local numberTable = {10, 20, 30, 40, 50, 60, 70}

-- Function to shuffle a table
local function shuffleTable(tbl)
    for i = #tbl, 2, -1 do
        local j = math.random(i)
        tbl[i], tbl[j] = tbl[j], tbl[i]
    end
end

-- Shuffle the table
shuffleTable(numberTable)

-- Function to get and remove a random number from the shuffled table
local function getRandomNumberFromShuffledTable()
    if #numberTable > 0 then
        return table.remove(numberTable)
    end
end

-- Call the function to get random numbers
for i = 1, 3 do
    local randomNum = getRandomNumberFromShuffledTable()
    if randomNum then
        print("Random number:", randomNum)
    else
        print("No more random numbers")
        break
    end
end

This approach shuffles the table and then extracts random numbers from it one by one, ensuring that each selected number is unique and the table is exhausted without repetition.

6 Likes
Quote In case the Person Decides to Remove this

Nice ChatGPT bro, Mind if I have it?

1 Like

Subject: Apology for My Usage of ChatGPT on Roblox Devforum

Dear [Recipient’s Name],

I hope this message finds you well. I am writing to sincerely apologize for my recent actions on the Roblox Devforum. I deeply regret and am truly sorry for using ChatGPT to assist people on the platform without considering the potential consequences.

I understand that the Roblox Devforum is a space for genuine interaction, help, and discussions related to game development. My decision to experiment with ChatGPT and use it to assist others was a thoughtless one, and I now realize that it was inappropriate and went against the spirit of the community.

I would like to emphasize that I never intended to undermine the purpose of the Devforum or diminish the value of real human interaction. My intentions were purely to explore the capabilities of the technology, but I now understand that I should have chosen a more appropriate and respectful environment for such experimentation.

I sincerely apologize to the Roblox community, the developers, and all those who may have been affected by my actions. I fully accept the responsibility for my mistake and am committed to rectifying the situation.

Moving forward, I will refrain from using any automated tools or AI systems in contexts where they could be seen as disrespectful or detrimental to genuine human engagement. I have learned a valuable lesson from this experience and will make every effort to contribute positively to the Roblox Devforum and uphold its standards.

Thank you for taking the time to read this apology. I appreciate your understanding and hope that you can find it in your heart to forgive my lapse in judgment. If there’s anything I can do to make amends or demonstrate my commitment to the community, please let me know.

Sincerely,

[Your Name]

1 Like

FYI, that won’t error. Using math.random(n) implicitly converts it to math.random(1, n)

1 Like

Oh, I’m dumb. Thanks for telling me!

1 Like

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