[Home] [Downloads] [Search] [Help/forum]


Register forum user name Search FAQ

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.


See Also ...

Lua keywords/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 base functions
Lua bc (big number) functions
Lua bit manipulation functions
Lua coroutine functions
Lua debug functions
Lua io functions
Lua LPEG library
Lua math functions
Lua os functions
Lua package functions
Lua PCRE regular expression functions
Lua script extensions
Lua SQLite (database) interface
Lua string functions
Lua syntax
Lua table functions
Lua utilities
Scripting
Scripting callbacks - plugins

(Help topic: lua=if / then / else)

Documentation contents page


Search ...

Enter a search string to find matching documentation.

Search for:   

Quick links: MUSHclient. MUSHclient help. Forum shortcuts. Posting templates. Lua modules. Lua documentation.

Information and images on this site are licensed under the Creative Commons Attribution 3.0 Australia License unless stated otherwise.

[Home]


Written by Nick Gammon - 5K   profile for Nick Gammon on Stack Exchange, a network of free, community-driven Q&A sites   Marriage equality

Comments to: Gammon Software support
[RH click to get RSS URL] Forum RSS feed ( https://gammon.com.au/rss/forum.xml )

[Best viewed with any browser - 2K]    [Hosted at HostDash]