Basic if statements

Posted by SR388 on Sun 09 Dec 2007 07:05 AM — 4 posts, 27,162 views.

#0
I've learned how to check variables and modify them based on certain data, such as the example below:

crit = tonumber (GetVariable ("crit")) or 0
crit = crit + 1
SetVariable ("crit", crit)

I'm curious how to enter a command based on a variable. For example,

crit = tonumber (GetVariable ("crit")) or 0
if crit = 1 [execute command]
if crit = 2 [execute some other command]

This way I can set up an automated chain of events from start to finish.
USA #1
something like this

if crit == 1 then
WHATEVER
elseif crit == 2 then
WHATEVER ELSE
end -- if

the --if is optional but can be recommended so you know that is the end of an if statement and not a loop or other block structure that uses the 'end' as a termination word.

-Onoitsu2
#2
Also, as your scripts become more complicated, indentation is your friend. Use an editor that has a fixed width font (aka monospaced, such as Courier New) and then make matching levels of nested blocks to line up vertically so you can see at a glance what code belongs to which block, like so:


function doSomething(stuff)
  for key, val in pairs(stuff)
    if val != nil then
      print(key .. ":" .. val)
    end --if
  end --for
end --doSomething()


How much you indent is a matter of personal choice. Holy wars are fought over whether two-space, three-space, four-space and tabs-instead-of-spaces is the "best".
USA #3
If you are looking to make a switch or case statement, it might also be useful to make a table of values or functions. See this post for a few more details: http://www.gammon.com.au/forum/?id=7891 Granted, most of that is just me being bored rather than being useful, but there is a nice little example of a set of if/elseif statements with return values.