bitburner-official / bitburner-src

Bitburner source code.
Other
774 stars 256 forks source link

SCRIPT: Identical modules with different names and/or on different servers share globals. #1494

Open tomprince opened 1 month ago

tomprince commented 1 month ago

Given

let val = 1;

/** @param {NS} ns */
export async function main(ns) {
  ns.tprint(val++);
}

I get the following surprising output.

[home /]> nano one.js
[home /]> run one.js 
Running script with 1 thread(s), pid 3 and args: [].
one.js: 1
[home /]> cp one.js two.js
File one.js copied to two.js
[home /]> run two.js 
Running script with 1 thread(s), pid 4 and args: [].
two.js: 2
[home /]> scp two.js n00dles 
two.js copied to n00dles
[home /]> connect n00dles 
Connected to n00dles
[n00dles /]> mv two.js three.js
Moved two.js to three.js
[n00dles /]> run three.js 
Running script with 1 thread(s), pid 5 and args: [].
three.js: 3

I'd naively expect the output of each script to be 1.

This is perhaps desired, to avoid having scripts that are copied to every server taking up a bunch of memory, but it seems like it should be something that is at least documented.

This is somewhat related to #642, in that the lifetime and scope of module level variables are not what people might otherwise expect.

tomprince commented 1 month ago

This is also related to #686.

d0sboots commented 1 month ago

Yes, this happens due to internal implementation reasons and the expected behavior is intentionally not specified, for implementation flexibility.

At this point enough people are relying on the ability to share variables across identically-named scripts on different servers that we probably can't/won't break that. The fact that we're doing it by code instead of filename is something we might change if needed in the future (although it seems unlikely).

tomprince commented 1 month ago

I think it is weird enough behaviour that it would make sense to document it, even if there is a large caveat in the documentation that the behaviour is subject to change.