I was reading this post of someone recreating Minecraft’s classic terrain generation which requires a Lua implementation of Java’s Random class for 1:1 results, since the original poster didn’t share his, I decided to create my own and share it with all of you.
Overview
The JavaRandom
Lua module emulates Java’s Random
class behavior for generating pseudo-random numbers. It includes functionalities for generating random numbers of various types, seeding the generator, and obtaining random values within specified ranges. This module uses BigInteger for 64 bit integers, credit to Blockzez. This is my first topic so expect editorial edits and future updates.
Where do I get it?
You can get it from here:
1.0.1:
- JavaRandom.rbxm (25.5 KB)
- Added 64 bit integer seed support as strings using BigInteger
- 4 December 2023
1.0.0:
- JavaRandom.rbxm (25.2 KB)
- 1 December 2023
Documentation
The module consists of methods and constants replicating Java’s Random class functionalities:
-
JavaRandom.new(seed: number | string)
: Creates a new JavaRandom object with an optional seed value. -
JavaRandom:next_signed(bits: number) -> number
: Generates a random signed integer with the specified number of bits. -
JavaRandom:next(bits: number) -> number
: Generates a random integer with the specified number of bits. -
JavaRandom:setSeed(seed: string | number)
: Sets the seed for the random number generator. If you want to use big integers (64 bit) seeds then use strings (“12345678910111213141516” for example). -
JavaRandom:nextInt(bound: number) -> number
: Generates a random integer within a specified range. -
JavaRandom:nextBoolean() -> boolean
: Generates a random boolean value. -
JavaRandom:nextFloat() -> number
: Generates a random floating-point number between 0.0 and 1.0. -
JavaRandom:nextGaussian() -> number
: Generates a random Gaussian (normal) distributed number. -
JavaRandom:nextDouble() -> number
: Generates a random double-precision floating-point number between 0.0 and 1.0. -
JavaRandom:nextLong() -> BigInteger
: Generates a random 64-bit integer.
Usage
To use the JavaRandom
module, create an instance and call the provided methods to obtain random values or perform operations.
Example:
local JavaRandom = require(game.ReplicatedStorage.JavaRandom)
-- Create a new instance with an optional seed
local rand = JavaRandom.new(54321)
-- Set a new seed
rand:setSeed(123456)
for i = 1, 10 do
print(rand:nextInt(100)) -- Adjust the argument to change the range of random numbers
end