CC: Tweaked

CC: Tweaked

57M Downloads

loadstring not preserving global enviroment

KoromaruKoruko opened this issue ยท 1 comments

commented

Mc: 1.12.2
CC Tweaked: 1.86.2

GlobalVar = "MyValue"
loadstring("print(GlobalVar)")()

this will output:

nil

Expected:

MyValue

note this is unexpected behavior as in standard lua the global context for the return of loadstring would be the same as it's caller but in CC this is not the case

you can confirm this by using https://repl.it/languages/lua to run the sniplet online with lua 5.1.5

commented

Every CC program runs within its own environment, which effectively inherits from _G. Thus, when you do GlobalVar = "MyValue", you're actually setting it for the current environment - it vanishes after the program terminates.

However, load (and its derivatives like loadstring) load using the global environment, and so GlobalVar is not visible. You can see this by comparing the two runs here:

image

One can work around this in a couple of ways:

  • _G.GlobalVar = "MyValue": Set it in actual global table.
  • load("print(GlobalVar)", nil, nil, _ENV): Load your string in the current environment.
  • Don't use globals! They're bad form.