I'm trying to find a way to choose a random number from a specified list. Something like this:

Code: Select all

`x = x + choose(1, 2, 3, ...)`

Is there a way to do this?

Hiya, this is my first post here, so if I'm breaking any rules here please let me know.

I'm trying to find a way to choose a random number from a specified list. Something like this:

I've searched through the Lua documentation and the Love documentation and didn't see anything.

Is there a way to do this?

I'm trying to find a way to choose a random number from a specified list. Something like this:

Code: Select all

`x = x + choose(1, 2, 3, ...)`

Is there a way to do this?

Sure. It depends on what you mean by "random list of numbers," though.

For instance, if you want a random integer, try
where lowest and highest are the (inclusive) range of the values you would expect.

If you have a "list" (integer-indexed table) of pre-generated values and you would like to choose one randomly, try:

For instance, if you want a random integer, try

Code: Select all

`love.math.random( lowest, highest )`

If you have a "list" (integer-indexed table) of pre-generated values and you would like to choose one randomly, try:

Code: Select all

```
list = { 1, 2, 47, 3, math.pi }
print( list[love.math.random( #list )] )
```

GitHub | MLib - Math and shape intersections library | Walt - Animation library | Brady - Camera library with parallax scrolling | Vim-love-docs - Help files and syntax coloring for Vim

The second method is exactly what I was looking for. Thanks!

- Roland_Yonaba
- Inner party member
**Posts:**1563**Joined:**Tue Jun 21, 2011 6:08 pm**Location:**Ouagadougou (Burkina Faso)-
**Contact:**

I recently added in the 1.6.0 release of Moses (a utility-belt library for Lua I am maintaining), two utility functions: sample and sampleProb.

The first one will pick randomly one value in a supplied list. We can even specify a certain number of values to pick. It roughly works as davisdude suggested.

The latter might be slightly more interesting, as it performs probabilistic sampling . It considers every single element in the array and given a probability, will decide (randomly) if the element should be part of the returned sample or not.

The first one will pick randomly one value in a supplied list. We can even specify a certain number of values to pick. It roughly works as davisdude suggested.

The latter might be slightly more interesting, as it performs probabilistic sampling . It considers every single element in the array and given a probability, will decide (randomly) if the element should be part of the returned sample or not.

Users browsing this forum: No registered users and 31 guests