Just a question about variables

i always thought in order to make a variable you had to do “Local X = Y”
but i found in one of my old scripts that i forgot to put the local thing, and never realized. The script works fine but i thought u always needed the word Local infront of it
Heres the image of it:

1 Like

You don’t need it but it’s “tradition” and apparently is faster so it’s better practice

You don’t have to put local in front of variable declarations, but you should.

  1. Making the variable local increases script performance
  2. Making it local doesn’t pollute the script autocomplete
local function hello()
    world = "value"

wor -- While typing, you can see 'world' here even though it doesn't exist here (nil) nor is it used here

Variables can simply just be a name with a value. No need for the local keyword.

a = 10

There are differences between a local and a global variable.

If you make a global variable in a function, everything outside the function can also use it as well.

local function a()
    b = 5

a() -- Sets b to 5
print(b) -- Prints 5

They are saved as part of the script. So if you run this code in the output:

print(a) a = 5

Running it for the first time, it prints nil. But running it again, it prints 5.

1 Like

Defining without the “local” keyword gives the variable global scope.

item = "orange"

Defining with the “local” keyword gives the variable local scope.

local count = 17

This is example of global scope:

local function globalScope()
  item = "apple"
print(item) -- Will return "apple"

Local scope can only be accessed within that function:

local function localScope()
  local item = "apple"
print(item) -- This will return nil

In this case, we’ll see two different variables at the outermost scope.

local localScope = "apple"
globalScope = "banana"

However, you should define this as local scope since the engine would have to check each individual scope if it were global, making it much slower than local scope. If it’s local scope then it only needs to check the current scope it’s in.

More information about scope: Scope (computer science) - Wikipedia