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

Leave function

Started by solber, 21 May 2015 - 01:40 PM
solber #1
Posted 21 May 2015 - 03:40 PM
Hi guys, i got a problem and I need your help to fix it, so i'm working on program, it work but i cant leave function so my program not work totaly, this is the program : http://pastebin.com/3WsQrvGX

And this is the function :
  • function getbtn()
  • request(81, requestG[i])
  • id, message = rednet.receive()
  • if(id==81) then
  • if(message=="true") then
  • can=false
  • if(i==1) then
  • bt1ac()
  • elseif(i==2) then
  • bt2ac()
  • elseif(i==3) then
  • bt3ac()
  • end
  • else
  • can=false
  • if(i==1) then
  • bt1inac()
  • elseif(i==2) then
  • bt2inac()
  • elseif(i==3) then
  • bt3inac()
  • end
  • end
  • end
  • if(i==3) then
  • print(can)
  • end
  • if(i <= 3) then
  • i=i+1
  • getbtn()
  • end
  • end – end function getbtn
Cranium #2
Posted 21 May 2015 - 04:23 PM
Moved to Ask a Pro.
Creator #3
Posted 21 May 2015 - 04:28 PM
put your code in code tags
Kaikaku #4
Posted 21 May 2015 - 06:35 PM
The function should already end when i becomes 5 (for the pastebin version or 4 for the version in this thread).

If you want to exit earlier you can add for example 'return true'.
Edited on 21 May 2015 - 04:37 PM
valithor #5
Posted 21 May 2015 - 07:11 PM
I am actually suprised no one else has said this yet…

The function you posted could be better written as this:


function getbtn()
  for i = 1, 4 do
	request(81, requestG[i])

	id, message = rednet.receive(5)

	if(id==81) then
	  if(message=="true") then
		can=false
		if(i==1) then
		   bt1ac()
		elseif(i==2) then
		   bt2ac()
		elseif(i==3) then
		   bt3ac()
		elseif(i==4) then
		   bt4ac()
		end
	  else
		can=false
		if(i==1) then
		   bt1inac()
		elseif(i==2) then
		   bt2inac()
		elseif(i==3) then
		   bt3inac()
		elseif(i==4) then
		   bt4inac()
		end
	  end
	end
	if(i==4) then
	  print(can)
	  print(i)
	end
  end
end -- end function getbtn

This will do the exact same thing, but without the need to keep track of the variable yourself, or to use recursion.

This will utilize a for loop. The i=1 is defining i as the counter variable. Each iteration it will increase by one until it reaches the second number in this case 4, and it will run all code between the start of the for loop and the end associated with it until then.

As KaiKaku said, this code will only run 4 times. There is no reason it wouldn't end after the 4th itteration.
Edited on 21 May 2015 - 05:30 PM