Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Can a function use local variables without passing as a parameter?

Asked by
Necrorave 560 Moderation Voter
9 years ago

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!

0
They should change. `value` and `text` are GLOBAL variables, *not* local variables. BlueTaslem 18071 — 9y

1 answer

Log in to vote
1
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
9 years ago

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)
0
This is what I ended up fooling around with a bunch. I ended up doing something similar. Thanks for the in depth answer. Necrorave 560 — 9y
Ad

Answer this question