• General lua question: What is the difference between if/then and while/do?
    3 replies, posted
The reason I ask is because I first thought that if/then statements could be used in individual instances in which a condition only appears once and while/do would be used while a condition exists for a period of time (hence, it being while/do.) But After putting some more thought into it, I figured that if/then is meant to handle conditions that exist for one tick, while while/do handles conditions that exist for multiple ticks. But if that's the case, what's the point of using while/do as opposed to using if/then repeatedly and vice-versa? tl;dr: read title
Loops (while/for/repeat) can't handle conditions that "exist for multiple ticks", don't know where you heard that from. If statements are meant to execute a block of code if their condition evaluates to true, loops are meant to repeat a block of code until it's stopped (in the case of while loops, when its condition no longer evaluates to true). There's quite a big difference. if: [lua] if true then print( "Hello world" ) end > Hello world [/lua] while: [lua] local i = 1 while i <= 2 do print( "Hello world" ) i = i + 1 end > Hello world > Hello world [/lua] for: [lua] for i = 1, 3 do print( "Hello world" ) end > Hello world > Hello world > Hello world [/lua]
If represents a single logic branch that will only execute once per call. [code] if condition then DoSomething( ) else DoSomethingElse( ) end[/code] While will run until a condition is met, and can run forever if you aren't careful. [code] Pickers = 3 apples = 0 while apples < 10 do if Pickers > 0 then Pickers = Pickers - 1 apples = apples + 3 else apples = apples - 2 Pickers = Pickers + 1 end end[/code] Then, we have a repeat loop, which is similar to a while loop. [code]Pickers = 3 apples = 0 repeat if Pickers > 0 then Pickers = Pickers - 1 apples = apples + 3 else apples = apples - 2 Pickers = Pickers + 1 end until apples > 10[/code] The main functional difference between while and repeat are that a while loop will not run if the initial condition is met, but a repeat will run at least once always. And, of course, there is the standard for loop [code] for counter = 1, 10 do print( counter ) end for counter = 10, 1, -1 do print( counter ) end[/code] For flow control, we have two commands. break, which will force you out of the current loop continue, which will stop the current execution and start it again. [code]for counter = 1, 100 do if counter % 4 == 0 then --Don't do anything if divisible by four continue end print( counter ) end[/code] That should print 1 through 100, skipping anything divisible by four, so 1, 2, 3, 5, 6, 7, 9, ... 97, 98, 99
Wonderful, thank you all.
Sorry, you need to Log In to post a reply to this thread.