Local variables have their scope limited to the block where they are declared. A block is the body of a control structure, like for an example, if you declare a local variable inside a function, you can’t get the value from it outside that function.
This also apply if it’s declared inside an if block, do-end block or inside the loops(Like while-do-end, for-do-end and repeat-until).
local makes variables respect “scopes”. Scopes are like parts of code where a start and end are given. For example, If/Then statements create a scope.
if _ then
end
This creates a scope between THEN and END. Programmers use tabs or spaces to indent code, to visually show scopes. The scope starts at THEN and ends at END. Any variables CREATED inside the scope, will be deleted whe the scope ENDS. incapaz’s example of creating a local variable inside of a scope and trying to access it outside is a good example of what happens.
You should always use local variables. In my example if the variable x was global then it would escape the scope and print 10 in both places. This is bad since it pollutes the global environment and makes you more prone to name collisions. There is also that negligible speed boost.
A variable can only contain one value, the point is what if you end up needing to reuse the same identifier but not the same variable itself. And yes local access is slightly faster than global since the former grabs from the stack whereas the latter grabs from the environment.