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

(if i == nil) won't work

Started by FhatTheWuck, 07 July 2012 - 11:54 AM
FhatTheWuck #1
Posted 07 July 2012 - 01:54 PM
Hello everybody

I'm just experimenting with my code. And i really don't know why it's not working correct.


while true do

local i

if i == nil then
  i = 0
end

os.sleep(1)
rednet.broadcast(sFWName)

event, id, text = os.pullEvent("rednet_message")

if text == "message_received" then
  print("Message received")
  break
else
  print("Message not received")
  i = i + 1
end

if i == 2 then
  i = nil
  break
end

end

Even if i contains 1, the code executes this part of the code. The Problem is, that it never gets out of the loop.

if i == nil then
  i = 0
end

Please can you explain why that code isn't working?
Pinkishu #2
Posted 07 July 2012 - 02:10 PM
Uhm I think since its a local variable made inside the loop it get cleaned once the loop ends?

So put local i before the while and remove it from inside the loop
FhatTheWuck #3
Posted 07 July 2012 - 05:50 PM
Oh

Yeah, that was really a dumb fault.
In every singe repeat of the loop the local variable i gets new "initialized".
Pinkishu #4
Posted 07 July 2012 - 06:06 PM
Well it forgets about local variables in every new loop if they were defined in the loop i think? Not sure on that one but i think so :P/>/> Will test that~

edit: yes thats how it works
MysticT #5
Posted 07 July 2012 - 06:13 PM
The local variable is local to the loop, so when it restars the variable is "created" again.
Pinkishu #6
Posted 07 July 2012 - 07:03 PM
The local variable is local to the loop, so when it restars the variable is "created" again.

Yeah if you create it that is, if not its just forgotten