Random:GetState() and Random:SetState()

As a developer I may need to get a Random’s state in the form of a basic data type (string/number). This is useful for displaying debug data or for serializing it for storage in datastores, for example.

string Random:GetState()
void Random:SetState(string State)

An instance shouldn’t have an inaccessible state that exists in the ether and can’t be replicated. I should be able to deconstruct an instance into basic data types, and then use that data to reconstruct a copy. Enabling developers to do this enables them to do anything they could possibly want to do with the instance and its state.

11 Likes

Use Cases:

  • When generating rivers in a smooth terrain map, sometimes there’s a hole in a river. I save the state of the RNG before I begin generating water, and then when I want to test fixes to the issue, I just have to generate the water instead of the whole map since I can resume from the state post-map generation
  • When generating random appearances for characters in my game, occasionally I’ll get an error. To make this easier to debug, I’d keep a reference to the state and then on error I could use that state to instantly trigger the error for further testing rather than waiting through 50 or 100 appearance generations
3 Likes

State is actually a number, not a string.

The Random API is intentionally agnostic to the implementation details of the RNG algorithm and state size/format.

The use cases I’ve seen so far (serialization, debugging) can be met by storing the initial seed along with a count of how many times NextNumber and NextInteger have been called.

1 Like

I’d love to have this API created. It’d be easier than manually having to store the information I put into the instance beforehand, making it harder to cross reference against multiple other instances of ‘random’ while debugging.

I don’t want to have to write a wrapper around Random just to store the state it’s already storing.

If Random stored a count and seed that we could access, we wouldn’t need to write a wrapper, and could use the count and seed to store the state. Maybe this data is already available, but I can’t find any API documentation to check yet.

3 Likes

It would be useful to expose the seed and number of times it has been called then. Additionally, a fast forward method would also be nice that took a number of iterations. This would solve OP’s use case in a somewhat usable way and allow the API to be agnostic to implementation details.

2 Likes