if / then / else
You can use if condition then ... end to test a condition and execute code conditionally, eg.
You can of course reverse a condition by using not like this:
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.
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
- assignment
- break
- comments
- data types
- do
- for (generic)
- for (numeric)
- function
- identifiers
- keywords
- local
- logical operators
- precedence
- relational operators
- repeat
- return
- string literals
- tables
- while
Topics
- Lua LPEG library
- Lua PCRE regular expression functions
- Lua SQLite (database) interface
- Lua base functions
- Lua bc (big number) functions
- Lua bit manipulation functions
- Lua coroutine functions
- Lua debug functions
- Lua io functions
- Lua math functions
- Lua os functions
- Lua package functions
- Lua script extensions
- Lua string functions
- Lua syntax
- Lua table functions
- Lua utilities
- Scripting callbacks - plugins
- Scripting