This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
Microwarrior's profile picture

Using local

Started by Microwarrior, 04 July 2015 - 07:17 PM
Microwarrior #1
Posted 04 July 2015 - 09:17 PM
I want to start using local for variables because I heard it is safer and more efficient.


allowed = true
while allowed do
    local testVar = "testing"
    allowed = false
end
print(testVar)

My question is, how would I be able to get the testVar variable contents out of the loop and ideally keeping it a local variable?
Dog #2
Posted 04 July 2015 - 09:27 PM
Use a forward declaration like so…

local testVar
local allowed = true
while allowed do
  testVar = "testing"
  allowed = false
end
print(testVar)
Edited on 04 July 2015 - 07:28 PM
TheOddByte #3
Posted 04 July 2015 - 10:44 PM
I also want to point out that locals can be used like this

local text = "bar"
while true do
	local text = "foo" --# The text variable is not the same as the one outside the loop, as it has overriden it in this loop, statement or whatever
	print( text ) --# Outputs foo
	break
end
print( text ) --# Outputs bar
As you can see by the example code, in statements and such, two variables with the same name is like two different variables.
So the variable inside the loop will be "foo" until it gets out of the loop, and once it does that it becomes "bar"
Edited on 04 July 2015 - 09:39 PM
Microwarrior #4
Posted 05 July 2015 - 12:52 AM
Thanks for all the help, now I wont be leaking passwords!
Lion4ever #5
Posted 05 July 2015 - 09:47 AM
did you use the code only for demonstration purposes? if not:

local testVar
local allowed = true
if allowed then
  testVar = "testing"
end
print(testVar)

This does is shorter and you can use allowed futher down in the code, if you need to.