Boolean: Difference between revisions

From Legacy Roblox Wiki
Jump to navigationJump to search
>Sduke524
(I got rid of the wrong part, sorry.)
>NXTBoy
(→‎Not: Trying to delete the stupid operator pages)
Line 54: Line 54:


===Not===
===Not===
{{main|not operator}}
The '''not''' operator returns true if the argument is false or [[nil]], otherwise it will return false.
The '''not''' operator returns true if the argument is false or [[nil]], otherwise it will return false.


<code lua>
<code>
print(not false)      -- true
print(not false)      -- true
print(not nil)        -- true
print(not nil)        -- true
Line 66: Line 64:
print(not 1)          -- false
print(not 1)          -- false
</code>
</code>
{{Example|
One thing that the not operator is useful for is toggling something. To make a button toggle the visibility of a GUI, you can do:
<code lua>
button.MouseButton1Click:connect(function()
    frame.Visible = not frame.Visible
end)
</code>
}}


===And===
===And===

Revision as of 11:06, 21 February 2012

A Boolean, or Bool value, is a very simple data type. It is either a true or false value.

In Lua, when something is converted to a boolean, if the value is false or nil then it will be false, otherwise it is true.

Using Boolean's

Booleans are most commonly used with conditional statements. MyBool = true

if MyBool then

   --If "MyBool"'s value is true, this code is run.

else

   --If "MyBool"'s value is false, this code is run.

end

Converting booleans into strings

When converted to a string, booleans will return "true" or "false"

print(tostring(true))
print(tostring(false))

true

false

If you wanted it to print something other than true or false, you will have to use a conditional statements

local enabled = false

if enabled then

   print("Enabled")

else

   print("Disabled")

end

However, there is a cleaner way of doing this. You can use the following idiom:

print(enabled and "Enabled" or "Disabled")

and get the same results.

Operators

Not

The not operator returns true if the argument is false or nil, otherwise it will return false.

print(not false) -- true print(not nil) -- true print(not true) -- false print(not "A string") -- false print(not 0) -- false print(not 1) -- false

Example
{{{1}}}


And

Main article: and operator

The and operator returns the first argument if it is false or nil, otherwise it will return the second argument.

print(4 and 5) --> 5 print(nil and 13) --> nil print(false and 13) --> false

print(true and true) -- true print(true and false) -- false print(false and true) -- false print(false and false) -- false

Or

Main article: or operator

The or operator returns the first argument if it is neither false nor nil, otherwise it will return the second argument.

print(true or true) -- true print(true or false) -- true print(false or true) -- true print(false or false) -- false

print(4 or 5) --> 4 print(false or 5) --> 5

See Also