I'm having issues with a localscript. I am trying to convert one leaderstat to another leaderstat on a surfaceGUI. The localscript is located inside of the textbutton that handles the transaction
this is the localscript:
player = game.Players.LocalPlayer cool = player.leaderstats.CoolStuff.Value stuff = player.leaderstats.Stuff.Value buybutton = script.Parent buybutton.MouseButton1Click:connect(function() if cool >= 5 then cool = cool - 5 stuff = stuff + 15 end end)
Your error lies in the fact that you wrongly assume that the cool
and stuff
variable are references to the actual property of the IntValue
. If the value of the IntValue
changes, the variables you have defined won't update; only its Value
property will change. In order to fix this, you can remove the cool
and stuff
variables and only make direct accesses to the Value
property of the IntValue
. You could also modify the variables to hold the IntValue
itself.
player = game.Players.LocalPlayer cool = player.leaderstats.CoolStuff stuff = player.leaderstats.Stuff buybutton = script.Parent buybutton.MouseButton1Click:connect(function() if cool.Value >= 5 then cool.Value = cool.Value - 5 stuff.Value = stuff.Value + 15 end end)
It is important to note the difference between a reference and a value. Think of a reference as holding an actual memory location while a value just holds some normal information (such as a number). For example in Lua, tables are passed by reference.
local tableOne = {foo = "String" , random = 8 , goo = false} local tableTwo = {foo = "String" , random = 8 , goo = false} local tableOneRef = tableOne --tableOne and tableOneRef both represent the same table now --tableTwo is a different table tableOne.foo = "Hello Earth!" print(tableOne.foo) --> "Hello Earth!" print(tableOneRef.foo) --> "Hello Earth!" print(tableTwo.foo) --> "String"
The tableOne
and tableOneRef
variables both hold the exact same table or memory location while the tableTwo
variable is a different table even though it holds the same values.
On the other hand, datum such as integers and booleans are passed by value.
local num = 5 local numValue = num num = 10 print(num) --> 10 print(numValue) --> 5
Even when numValue
is set to num
, both of these variables have different memory allocated and thus changing one value does not change the other.