Jump to content

[QUESTION] Deterministic Javascript?


Splizard
 Share

Recommended Posts

Are there any concerns about non-deterministic behavior in Javascript code, or is it guaranteed to be deterministic for modders?
For example 'for ... in' loops do not guarantee the same iteration order (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in#Array_iteration_and_for...in).
Should this concern me when I am creating Javascript components?
(I am aware that the GUI Interface is not allowed to affect game state).

Link to comment
Share on other sites

2 hours ago, Splizard said:

For example 'for ... in' loops do not guarantee the same iteration order

This note doesn't make Javascript nondeterministic. It just means that it depends on an implementation. Because different engines for different types may use different structures behind objects/arrays for more optimal storing.

Also this reference suggests to use `for ... of` or `.forEach(...)`, when the order of the iteration is important. But `for ... in` is used for cases, when you just need to change/find a property, without knowing its index (the not fixed order may make it a little bit faster). So Javascript as the language is deterministic.

Link to comment
Share on other sites

In addition to what Vladislav said, there had been a number of catches to get the simulation deterministic.

For example the Math.random function was replaced in ScriptInterface::ReplaceNondeterministicRNG by a deterministic boost RNG that is initialized with a seed that the host choses at gamestart. Some other Math prototype functions were replaced in globalscripts/Math.js to be platform-consistent.

https://trac.wildfiregames.com/wiki/SimulationRequirements#Determinism

When you create a new simulation component, you should be more worried that it is serialization-safe, otherwise there will be an out-of-sync on rejoin or savegame load. The most important part is to have the simulation not change it's code through GUI calls as you mentioned. Sometimes one does have to do that (optional range visualization or diplomacy colors). Then one has to pay extra attention that the GUI dependent variables don't change the simulation state.

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

×
×
  • Create New...