FFXIAH.com

Language: JP EN DE FR
users online
GearSwap Tutorial Pt3

GearSwap Tutorial (v0.1)


PART 3



A little more detail on conditionals.

Sometimes we want to do something if a conditional is true, and other times we want to do something when it's not true. We may also have several things we want to check, and do something only if a particular condition is true.

For that, we have the 'else' and 'elseif' commands.
Code
    if item1 == condition1 then
        -- only if item1 == condition1
    elseif item2 == condition2
        -- only if item1 is *not* equal to condition1, *and* item2 == condition2
    else
        -- only if none of the if and elseif checks before this were true
    end
    -- Note: this 'end' is the endpoint for the first 'if'; don't forget it


Any computer program is ultimately just a huge series of if/then sequences, deciding what to do when /this/ happens, or what to do when it /doesn't/ happen, or what to do when two things happen at the same time, etc.

Also remember that there's a difference between:
Code
    if item1 == true then
        -- action1
    end
    
    if item2 == true then
        -- action2
    end


and
Code
    if item1 == true then
        -- action1
    elseif item2 == true then
        -- action2
    end


In the first code block, if item2 is true than action2 will happen, even if item1 was true. In the second code block, if item1 was true then item2 will never be checked, and action2 will never happen.

It's a subtle difference, and often won't make any real difference to what happens when the program is run. But it's a flaw that I see time and time again when people ask me to review their scripts -- when what you're trying to check for is necessarily exclusive (ie: if item1 was true then action2 should never happen), the code is still built as if it were not exclusive, and that can lead to hard-to-diagnose errors.



Navigation
Part 1 - Basic Sets and Events
Part 2 - Conditionals and Testing
Part 3 - More on Conditionals
Part 4 - Tables
Part 5 - Abstractions
Part 6 - Asking the Right Questions
Part 7 - Library Tools
Author: Motenten
Date Created: 2014-04-25 18:02:21
Date Last Modified: 2014-05-15 14:40:13
Updates: 4
Bytes: 2452