Chances of executing a code, how do I go about that?

Hello!

I am currently wondering how I can have chances/% of an event happening?

I tried looking up on the devhub or on YouTube but didn’t find much results.

Here’s a brief example of what I want to achieve.

-- Code of the chances, can be a bit like a wait() command if it helps 

—[[
There’s a 50% chances of being true.

If false then repeat wait(1), as a delay, until it is true.

When true we move on the next line of codes.
—]]

—

--Code executed after the chances were made. So if true, these lines of codes would execute.
print(“Moving”)

Thanks for reading and helping! :grin:

1 Like

From what you’ve given, you can use math.random for that I believe

local val = math.random(1,2) == 1 and true or false

while not val do
	wait(1)
	val = math.random(1,2) == 1 and true or false
end

--Code once true

This will act a chance. If the random number was 1, it becomes true, otherwise, false.

Not sure if this is what you wanted, didn’t understand that well

2 Likes

I will try it! Thank you! :heart: I will comeback to say if it was good or not.

1 Like

Hopefully it does as you wanted, although I’m not too sure if I understood what you had mentioned well.

To explain what it does, it first sets a value in the variable, if the random number was 1, it sets true into the val, otherwise, false. If val is true by the time it reaches that while loop, it just continues on, otherwise, does what you wanted (wait 1 second and try again until the value is true)

1 Like

Hey there!

I believe the following would work.

local Chance = math.random(1,2)

if Chance == 1 then
print("Moving")
else
print("Not moving")
end
2 Likes

I will try it too! Thank you, I will see which ones fits what I’m trying to do.

I think both would work, the if statements should operate the same way.

Have a good one!

1 Like

how are you using operators in a variable?

1 Like

Tenary operator. That line is the same as

local val 

if math.random(1,2) == 1 then
   val = true
else
   val = false
end
3 Likes

Just bc im bored here’s a bit of detail of what I’m trying to do.

I’m making a FNAF fangame and rn the ‘ai’ works like this, I’ll brief it up. Just to let you know.

wait(5)
game.ServerStorage.Chr1:Clone().Parent = game.Workspace
game.Workspace.Chr:Destroy()

I wanted to include a bit of randomness so it’s not too predictable and boring. Meaning my game won’t be really good.

1 Like

After trying @EmbatTheHybrid‘s way, it worked! Thank you! Now there was a few changes like rn it’s (1, 100) <= to make it in percent but I decided I will make it (1,20) to represent FNAF AI.

1 Like