if / then / else

You can use if condition then ... end to test a condition and execute code conditionally, eg.
if button_pressed then
  start_motor ()
end  -- if button pressed
If you want to do something else if the condition is not true you can use an else clause:
if button_pressed then
  start_motor ()
else
  turn_on_lights ()
end  -- if
For multiple tests you can use elseif which avoids having to use end multiple times:
if action == "heal" then
  heal_player ()
elseif action == "sleep" then
  goto_sleep ()
elseif action == "attack" then
  attack_mob ()
else
  print "invalid action"
end  -- if
The only conditions that are false are the values false and nil - every other value is considered true.

You can of course reverse a condition by using not like this:
if not asleep then
  eat_food ()
end  -- if not asleep



It is considered good programming practice to indent the contents of an if statement, to make it clear what parts are being executed conditionally.

It is also a good idea to put a comment on the end indicating what it is the end of (as in the examples above). This is because the keyword end can end if statements, while statements, for statements, do statements, and function bodies.

Lua keyword/topics

Topics