Is it possible for a function to use a local variable without calling it in a parameter?
I have a quick little thing here that I thought would work, but it does not.
value = script.Parent.Button.value.Value text = script.Parent.Display.SurfaceGui.Amount.Text function touch(part) wait(.5) part:Destroy() value = value + 5 text = "Money: "..tostring(value) end script.Parent.Touched:connect(touch)
I do not get any error, but value
and surfaceGUI
do not change at all.
If you could explain what the issue may be that would be swell!
Thanks!
Yes, this works. Usually, it's considered bad practice, but sometimes it makes things simple enough that it's worth it.
Note that value
and text
are global variables as opposed to local variables.
The problem here is not the scope of the variables -- the function can use and modify them just fact.
You are, in fact, changing value
and text
. However you are only changing those variables -- not the properties that they correspond to.
Your assignment on line 1 is analogous to
value = 0
That is, the thing on the right is just a number.
Just like you cannot expect the following to work to redefine 5
:
five = 5 five = 3 print(5 + 1) -- 4 ?
Your change of value
has no effect on its previous value which was the Value
property of an object.
In order to change the object, you have to explicitly change the object.
To make this a bit briefer, we can store the object as the variable and just set its properties:
value = script.Parent.Button.value text = script.Parent.Display.SurfaceGui.Amount ... value.Value = value.Value + 1 text.Text = "Money: " .. tostring(value)