how to make a random string array

how to make a random string array, i wanna get like this

array = {"3", "2", "5", "1", "4"}
array = {"5", "3", "1", "4", "2"}

try this

local n={1,2,3,4,5}
for i=1,#n do
   local u=math.random(1,#n)

This is a helpful little trick. I was having an issue where I want to take a few random numbers from a table, but I want to check each time that I’m not taking the same random number. I had been doing it the hard way, with lots of loops, so say another function had already selected lastvar and prevvar from the numbers 1,10, and I wanted a new random number “newvar” I was saying:-

newvar = math.random(1,10)
while newvar == lastvar or newvar == prevvar do
newvar = math.random(1,10)

But it wasn’t working 100% of the time, bizarrely. Sometimes newvar would be the same as prevvar, say. I couldn’t work out if this was something to do with the way number are stored? I’ve seen references to == being a bit temperamental, so where possible you should use >= or <=.

This method gets around that I think, but if you have any ideas why my old method wasn’t working then I would be interested to know.

Make a table of which numbers have been selected already, and for each number you choose, check the table and make sure it hasn’t been chosen already. Also, == isn’t “tempermental,” and you should only use <= or >= when you need them.

your method is very inefficient, and I don’t think it works properly. Why are you only comparing against the previous 2 numbers? What if there have been 4 previous numbers? Where do you update lastvar and prevvar?

And == works perfectly and is not temperamental. Any problem is positively definitely unquestionably and certainly in your code. I know it doesn’t feel that way, that happens to me too, but it’s true. :wink:

I know my method is inefficient, I’m just giving a snippet. Prevvar and lastvar have already been generated in my example (in a similar way) and that’s just the code to make sure that newvar is different. Except it isn’t sometimes!

At the moment my coding is mostly “intuitive” - I don’t yet know the best way to do things, and I count myself lucky if I can think of A way to do something with the limited arsenal of techniques I’ve built up! But every day I get a new weapon in my arsenal.

I will look up where I got the idea that == is something to be careful with. I think it may have been in a changing variable context. So you might start with x = 0, cycle through x= x+1 and want it to stop at x = 300, but better to test for x >= 300 than x == 300 because of the way the numbers are stored?

Perfectly prepared to accept my code is at fault though! Will check.

you may have seen the advice on == in the context of testing if something hits the edge of the screen. Then you definitely need to use >= and <= rather than ==

@Ignatz - thanks, i’ll study your code.