Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Random always picks last element in table?

Asked by 7 years ago

No matter if I do this:

local biomes = {"Plains","Desert"}
local currBiome = biomes[ math.random( #biomes ) ]

Or this:

local biomes = {"Plains","Desert","Plains"}
local currBiome = biomes[ math.random( #biomes ) ]

Or this:

math.randomseed( os.time() )
local biomes = {"Plains","Desert"}
local currBiome = biomes[ math.random( #biomes ) ]

It will always pick the last element from the table. What am I doing wrong?

1
The seed from os.time() or tick() does not vary much between short uses. That's why the output does not change in studio. Call an arbitrary math.random() if you want. cabbler 1942 — 7y

2 answers

Log in to vote
3
Answered by
duckwit 1404 Moderation Voter
7 years ago
Edited 7 years ago

Yikes! You've stumbled on a whopper. Have a look at this question on StackOverflow.

Basically, the ROBLOX version of Lua relies on a cross-platform C implementation of rand(3), which, if you're on OSX, isn't the best generator.

I tested this on OSX and, you're right, the first generated number is the same regardless of the seed! To mitigate this, call math.random() a couple of times before you actually use the output - the rest of the numbers are random, just not the first one.

1
FYI same on Windows 10. Programical 653 — 7y
Ad
Log in to vote
-1
Answered by 6 years ago

Duckwit is right, but I just wanted to explain this in a little more clarity for people who don't understand. If you want to choose a random terrain based on a value, we first need to set a variable for this. Let's call it TerrainNum. To create a random value of 3 terrains, this is what is needed:

TerrainNum = math.random(1,3) -- This is saying "Pick a random number from 1 to 3"
if TerrainNum == 1 then
 -- Plains
 -- Insert what you want to happen in here.
end
if TerrainNum == 2 then
-- Desert
-- Insert what you want to happen here.
end
if TerrainNum == 3 then
-- Swamp (or something)
-- Insert what you want to happen here.
end

This will set TerrainNum to a random number between 1 and 3, and depending on which one it is, it will execute a different line of code.

Answer this question