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

Asked

Viewed 88 times

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)

2 answers

2


Yes, they are accessible because if you don’t say the variable is local then it is implicitly global. When using an undeclared variable before, and not 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. I made an example by creating a local variable with wider scope and left the other global, to show that it works and is the same. I would always choose to declare the local variable before using it and when you need it in wider scope, state it in that scope before using it for the first time. Thus:

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)

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • Thank you Maniero, your comment was enlightening.

1

Variables a2 and d are places in that block and 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 it does not have the location tag before so you should be able to use later:

x1 = (-b + d)/a2
x2 = (-b - d)/a2

Browser other questions tagged

You are not signed in. Login or sign up in order to post.