Can you create variables within a block and use them later?

3
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)
    
asked by anonymous 28.08.2018 / 15:30

2 answers

2

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

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

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 running on ideone . And in Coding Ground . Also I placed GitHub for future reference .

    
28.08.2018 / 15:43
1

Variables a2 and d are places in this block and you can not use outside because they are declared as local:

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

Variables x1 and x2 are global because they do not have the location tag before so you can use later:

x1 = (-b + d)/a2
x2 = (-b - d)/a2
    
28.08.2018 / 15:40