Problem with variables?

Lets say I have the variable x which is a reference to a physical variables value:

x = game.Workspace.VariableX.Value

If I know would like to change the value of the PHYSICAL variable (VariableX.Value), and I would like to do that by using my reference x,

x = 5

the only thing that changes is x, and not VariableX.Value.

VariableX.Value stays the same, but the only thing that changed is x.

Is there a way to change VariableX.Value by using my reference variable x?

Nope, I am pretty sure you have to use x.Value.

Seconded. There isn’t any (reasonable) way to do this. I don’t even think it’s possible with setfenv.

This:

x = workspace.VariableX.Value

isn’t a reference to the “container”, it’s only the value.

If I have an IntValue in workspace,

local x = workspace.IntValue.Value

x is equal to 5 and only 5. It contains nothing but the number and won’t update or be updated if you change the value property of the IntValue.

Same thing with tables (which is fundamentally what Roblox’s workspace is).

local myTable = {
    ['Value'] = 5;
}
local x = myTable.Value -- this will be 5

-- then, if we do

myTable.Value = 10

-- x is still equal to 5. If we change the value of x, only the variable gets updated, not the property inside of the table.

local c = game.Workspace.VariableX.Value

c = (5 and pcall(function() game.Workspace.VariableX.Value == 5 end))

or if you dont want to use the function every time you change the variable alternatively you could do

local Variables = {
}

local mt = {
__newindex = function(t,i,v)
if workspace:FindFirstChild(i) then – VariableX exists in workspace
workspace:FindFirstChild(i).Value = v – Change variable value
rawset(t,i,v) – replace table value
end
end
}

setmetatable(Variables,mt)

Variables.VariableX = 9 – This would trigger __newindex

Challenge accepted.

I finished this script before realizing that apparently the function environment’s metatable is now locked in Roblox. Bums me out to no end actually. It was fun while it lasted. It was never practical anyways, but it was fun.

local variables = {}
do local mt = getmetatable(getfenv())
	mt.__index = function(self, key)
		if variables[key] then
			return variables[key][1][variables[key][2]]
		end
	end
	mt.__newindex = function(self, key, value)
		if variables[key] then
			variables[key][1][variables[key][2]] = value
		else
			rawset(self, key, value)
		end
	end
end
variables.x = {game.Workspace.VariableX, "Value"}
variables.color = {game.Workspace.BasePlate, "BrickColor"}
print(x)
x = 10
print(game.Workspace.VariableX.Value)
repeat color = BrickColor.Random() until coroutine.yield()
1 Like