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

What is the difference between these two variables?

Asked by 6 years ago

I have seen people make variables like this:

local variable = game.Workspace.Part

And like this:

variable = game .Workspace.Part

If someone could explain the difference between these two to me, or link me to something that does, it would be greatly appreciated.

1 answer

Log in to vote
1
Answered by
fredfishy 833 Moderation Voter
6 years ago
Edited 6 years ago

They limit the scope of a variable.

x = 5

function apple()
    x = x + 5
    print(x)
end

function alternateUniverseApple()
    local x = x + 5
    print(x)
end

function banana()
    print(x)
end

If we do this, we get 10 and 10:

apple()
banana()

If we do this instead, we get 10 and 5:

alternateUniverseApple()
banana()

This is because the local version of x ceases to exist once you get outside of the scope. I believe that in Lua, scope extends to the edges of a function, but I might be wrong on that front.

Edit

As link has pointed out, what I've said about scope is incorrect.

In Lua, scope is to do with "blocks", rather than functions.

Consider the following:

function testFunction()
  local x = 5
  print(x)
  if x == 5 then
    local x = x + 5
    print(x)
  end
  print(x)
end

You get out 5, 10, 5, rather than the 5, 10, 10 you'd expect if scoping was to the edge of functions

Further information here

End edit

Why do you want this? Two good reasons:

  • It allows the garbage collector to clean up variables you aren't using any more once they go out of scope, meaning your script uses less memory

  • It means that you can reuse a variable name in one place without changing it in another

The idea of scope can be a little weird at first, so you probably want to have a little play around with it.

0
That's right, variables are tied to the *blocks* they are declared in, not to functions. Non-local variables, called global variables, should not be used because they make your code messy. Link150 1355 — 6y
0
Have edited code regarding scope - however, disagree regarding global variables. There are two very good reasons to use them: fredfishy 833 — 6y
0
(1) Lua doesn't support constants, and global variables are far clearer than "magic numbers" fredfishy 833 — 6y
0
(2) If the flow of your code requires you to pass many variables around frequently at each step, it's often more readable to just use global variables rather than passing around 5 arguments to 5 different layers of your program. fredfishy 833 — 6y
Ad

Answer this question