Garry's Mod Wiki

Revision Difference

Global.Either#526818

<function name="Either" parent="Global" type="libraryfunc"> <description>An 'if then else'. This is `almost` equivalent to (`condition` and `truevar` or `falsevar`) in Lua. The difference is that if `truevar` evaluates to false, the plain Lua method stated would return `falsevar` regardless of `condition` whilst this function would take `condition` into account.</description>⤶ <description>A compact 'if then else'. This is *almost* equivalent to (`condition` and `truevar` or `falsevar`) in Lua.⤶ The difference is that if `truevar` evaluates to false, the plain Lua method stated would return `falsevar` regardless of `condition` whilst this function would take `condition` into account.</description>⤶ <realm>Shared and Menu</realm> <file line="359-L362">lua/includes/util.lua</file> <file line="362-L365">lua/includes/util.lua</file> <args> <arg name="condition" type="any">The condition to check if true or false.</arg> <arg name="truevar" type="any">If the condition isn't nil/false, returns this value.</arg> <arg name="falsevar" type="any">If the condition is nil/false, returns this value.</arg> </args> <rets> <ret name="" type="any">The result.</ret> </rets> </function> <example> <description>The following two `print` statements have identical results.</description> <code> local ply = Entity( 1 ) print( "Player " .. Either( ply:IsAdmin(), "is", "is not" ) .. " an admin" ) print( "Player " .. ( ply:IsAdmin() and "is" or "is not" ) .. " an admin" ) </code> <output>If Player 1 is admin, it will print "Player is an admin".</output> </example> <example> <description>Plain Lua alias version.</description> <description>An example of the differences between Lua's ternary operator and this function.</description> <code> print("You are: "..( LocalPlayer():Alive() and "alive" or "dead" ))⤶ ⤶ // conditional:⤶ ⤶ print( "Halflife? "..( (LocalPlayer():Health()==50) and "halflife" or "not halflife") )⤶ local myCondition = true⤶ local consequent = false⤶ local alternative = "Second string"⤶ ⤶ print(myCondition and consequent or alternative)⤶ print(Either(myCondition, consequent, alternative))⤶ </code> <outputfixedwidth>Fixed width</outputfixedwidth> <output> You are alive⤶ ⤶ Halflife? not halflife⤶ Second string⤶ ⤶ false⤶ </output> ⤶ </example>⤶ </example>⤶