How do i create global variables?

cup of cake

Member... or am i?
It's in the title, really. I find that most mods are structured in a way where they can define a global variable or function in one lua file, and then use it in another without any issues. (examples from pizza tower spice runners: "if not PTSR.isovertime then", and even "if PTSR.IsPTSR() == true then")
Obviously, i tried making both a variable and a function without the "local" prefix, but the game refuses to create them. Is there something i'm missing? Let me know.
 
srb2 only allows certain names to be set in the global environment through regular means by using metatables, speficially with a __newindex metamethod which checks if a certain name is allowed

if you want to add your own global variables, you need to add them to the global environment with the rawset function, which ignores metamethods:
Lua:
local very_cool_var = 1
rawset(getfenv(), "very_cool_var", very_cool_var)

once you put an value in the global environment, you can modify it freely as the __newindex metamethod is only triggered when adding a new variable

though, i can tell from the PTSR prefix in the examples that those variables reside within a table, which you can make like this:
Lua:
rawset(getfenv(), "mytable", {}) -- creates empty table in global environment
mytable.var1 = true -- allowed, since you're not modifying the global environment
 
Last edited:
srb2 only allows certain names to be set in the global environment through regular means by using metatables, speficially with a __newindex metamethod which checks if a certain name is allowed

if you want to add your own global variables, you need to add them to the global environment with the rawset function, which ignores metamethods:
Lua:
local very_cool_var = 1
rawset(getfenv(), "very_cool_var", very_cool_var)

once you put an value in the global environment, you can modify it freely as the __newindex metamethod is only triggered when adding a new variable

though, i can tell from the PTSR prefix in the examples that those variables reside within a table, which you can make like this:
Lua:
rawset(getfenv(), "mytable", {}) -- creates empty table in global environment
mytable.var1 = true -- allowed, since you're not modifying the global environment
Alright, thanks for the reply! I'll be testing that out later today. But i'm not gonna lie, those metamethods and rawsets kinda scare me :worry:
 
Alright, thanks for the reply! I'll be testing that out later today. But i'm not gonna lie, those metamethods and rawsets kinda scare me :worry:
metatables and metamethods are more advanced parts of lua, but you can do cool stuff with them once you learn how to use them (like read-only variables)
 

Who is viewing this thread (Total: 0, Members: 0, Guests: 0)

Back
Top