KubeJS

KubeJS

107M Downloads

Cannot declare constants with the same name in two different files

Pelemenguin opened this issue ยท 1 comments

commented

Minecraft Version

1.20.1

KubeJS Version

2001.6.5-build.16

Rhino Version

2001.2.3-build.10

Architectury Version

9.2.14

Forge/Fabric Version

NeoForge 47.1.106

Describe your issue

Place two files into server_scripts.

In a.js:

// priority: 2

const CONSTANT = 1
console.info(`from a.js: ${CONSTANT}`)

In b.js:

// priority: 1

const CONSTANT = 2
console.info(`from b.js: ${CONSTANT}`)

After reloading, in server.log:

[18:11:38] [INIT] KubeJS 2001.6.5-build.16; MC 2001 forge
[18:11:38] [INIT] Loaded plugins:
[18:11:38] [INIT] - dev.latvian.mods.kubejs.forge.BuiltinKubeJSForgePlugin
[18:11:38] [INIT] - dev.latvian.mods.kubejs.forge.BuiltinKubeJSForgeClientPlugin
[18:11:38] [INFO] a.js#4: from a.js: 1
[18:11:38] [INFO] Loaded script server_scripts:a.js in 0.089 s
[18:11:39] [ERROR] ! TypeError: TypeError: redeclaration of const CONSTANT.
[18:11:39] [INFO] example.js#5: Hello, World! (Loaded server scripts)
[18:11:39] [INFO] Loaded script server_scripts:example.js in 0.001 s
[18:11:39] [INFO] Loaded 2/3 KubeJS server scripts in 0.319 s with 1 errors and 0 warnings
[18:11:39] [INFO] Scripts loaded
[18:11:43] [INFO] Server resource reload complete!

This means that even if two constants are declared in different files, KubeJS still see them as the same identifier.

(By the way, functions may also have this problem. I once declared a function which has the same name as another one in another file, and this function does not work. I solved this problem by only changing one of them's name.
But I cannot reproduce this, so I only reported the constants' bug.)

Crash report/logs

No response

commented

This is intended behaviour.
If you want to have scripts run in different scopes you need to wrap them in self executing functions, like this:

(() => {

const something = "hi"
console.log(something)

})()

Note that constants do also have odd behaviour with for loops, where they get scoped to the outer scope of the for loop rather than the inner scope, so things like this will error:

for (const item of some_list) {
    console.log(item)
}

This is not intended but not likely to be fixed any time soon.
There may also be oddities with constants and if statements or functions, those also arent intended and are just a quirk of the JS engine KJS uses. Generally its safest to use let for 'inner constants' like that.