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

[Lua][Question] Infinite Loop in Lua?

Started by Hidden Monarch, 03 April 2012 - 03:21 AM
Hidden Monarch #1
Posted 03 April 2012 - 05:21 AM
Hello! I am trying to make an infinite loop in Lua. I've tried
::loop::
//code
goto loop
to no avail. Help!
Luanub #2
Posted 03 April 2012 - 05:25 AM
Use a while loop or a repeat loop to do an infinite loop


while true do
stuff
end

theend = true
repeat
stuff
until theend == false -- will never be false so keeps repeating

Also note there is no goto function in lua, and it is considered poor coding practices to use goto. It can cause some funky problems. Just create your code as a function and call the function instead…


function infiniteLoop()
while true do
stuff
end
end

infiniteLoop() -- to call the function
Edited on 03 April 2012 - 03:35 AM
GreaseMonkey #3
Posted 03 April 2012 - 05:35 AM
As far as you are concerned, labels and goto don't, never have, and never will exist and you should be ashamed for thinking that they do. (They're a Lua 5.2 feature and should be used as sparingly as possible. ComputerCraft uses a Lua 5.1 VM, and thus doesn't have these.)

Anyhow, various loops.

-- this should be fine, and it's what i use personally.
while true do
  -- stuff
end

-- this should also be fine.
-- EDIT: oops, ninja'd.
repeat
  -- stuff
until false

-- i would advise you stay away from this one.
-- it's valid, but definitely way above your level. plus i don't use it myself.
-- (the "return" is important - if you forget it, your program will crash horribly!)
do
  local function f()
	return f()
  end
  f()
end
Hidden Monarch #4
Posted 03 April 2012 - 09:54 PM
Thanks both of you! :)/>/>
Vksfn #5
Posted 03 September 2013 - 08:56 PM
Im making a tree cutter. I want my turtle to brake the logs as soon as the tree grows. The code is below on what I am using. If the tree is already grown, and I run the program (TreeChop) it chops down the tree fine. But if the tree grows again, it wont chop it down. i have to manually run the program. I want to make is automated. How would i do that?

While true do
  --Stuff
end
prozacgod #6
Posted 03 September 2013 - 09:55 PM
The way I did mine, was compare slot 1 (log of tree I'm cutting down) with what was in front of me (either air, or sapling) something like


function waitForTree()
  turtle.select(1)
  while true do
    if (turtle.compare()) then
      return
    end
    os.sleep(10)
  end
end

function cutTreeDown()
   -- Implement your chopping here...
end

function dropItems()
  -- drop all items but except for 1 item from slot 1.  (just assume its a log)
end

while true do
  waitForTree()
  cutTreeDown()
  dropItems()
end


This is approximate and should point you in the right direction.