Can you stop global variables?

Hello programmers!

I was wondering, can you stop/freeze _G. from changing?

I have a local script in starterplayerscripts which changes default movement of player with variable speed assigned to _G. and another script in StarterCharacterScripts which resets this variable after death, but when you died and didint respawn yet, you can still increase this value.

I know I can just change respawn time to minimum but freeze option would be also useful in other game aspects.

1 Like

You can stop any modifications to any table by using metatables.
I won’t explain a lot, you can read an article by Roblox about metatables here.

Here’s an example:

local locked = false -- Changing this value to true will lock the speed

local defaultSpeed = 16

_G.speed = defaultSpeed

setmetatable(_G, {
	__index = function(t, i)
		if tostring(i) == "speed" and locked then
			return defaultSpeed -- Returns the default speed instead of nil 
		end
	end,
	
	__newindex = function(t, i, v)
		if tostring(i) == "speed" and locked then
			-- Nothing happens and the value doesn't change
		end
	end
})
1 Like