Can one create variables within a block and use them afterwards?

do
   local a2 = 2*a
   local d = sqrt(b^2 - 4*a*c)
   x1 = (-b + d)/a2
   x2 = (-b - d)/a2
end          -- scope of `a2' and `d' ends here
print(x1, x2)
Author: Maniero, 2018-08-28

2 answers

Yes, they are accessible because if you don't say the variable is local then it is implicitly global. When you use a variable that has not been declared before, and has not been used local is a variable declaration that can be accessed throughout the code.

Some consider this a mistake and that it should not be used (it always has its usefulness there), but I would avoid it. I made an example by creating a local variable with broader scope and left the other global, to show that it works and is equal. I I would always choose to declare the local variable before using it and when you need it in wider scope, declare it in that scope before using it for the first time. Like this:

local a = 2
local b = 6
local c = 4
local x1
do
   local a2 = 2 * a
   local d = math.sqrt(b ^ 2 - 4 * a * c)
   x1 = (-b + d) / a2
   x2 = (-b - d) / a2
end
print(x1, x2)

See working on ideone. E no repl.it. also I put on GitHub for future reference .

 2
Author: Maniero, 2020-08-03 17:01:59

Variables a2 and d are locations in that block and you cannot use outside, because they are declared as location:

local a2 = 2*a
local d = sqrt(b^2 - 4*a*c)

Variables x1 and x2 are global because they don't have the location tag before so you should be able to use it later:

x1 = (-b + d)/a2
x2 = (-b - d)/a2
 1
Author: Pbras, 2018-08-28 13:40:54