7 posts
Posted 30 July 2015 - 08:01 PM
I wrote this program to turn a redstone output off after confirmation, but if I put in the 'n' option into the console to cancel it, it still shuts the redstone output off. Is there something Im doing wrong here (I'm new to Lua, sorry)?
local answer = io.read()
if answer == 'y' or 'Y' then
redstone.setOutput('right',false)
print('Power off')
elseif answer == 'n' or 'N' then
print('ok')
end
Edited on 30 July 2015 - 06:25 PM
1140 posts
Location
Kaunas, Lithuania
Posted 30 July 2015 - 09:44 PM
This condition here:
if answer == 'y' or 'Y' then
..is saying: if 'answer' is equal to "y", or "Y" is not nil or false then. To check for multiple conditions you'll have to make the checks separate:
if answer == 'y' or answer == 'Y' then
Same with the elseif.
7 posts
Posted 31 July 2015 - 01:34 AM
Thank you so much!
1852 posts
Location
Sweden
Posted 31 July 2015 - 01:35 PM
A tip, you can use string.lower so that you'd only have to check one possibility
local answer = string.lower( read() )
if answer == "y" then
rs.setOutput( "right" false )
print( "Power off" )
elseif answer == "n" then
print( "Ok" )
end
And you could even use logical operators in your function calls and declarations, this one may be a little harder to understand + that I'm bad at explaining things.
local answer = string.lower( read() )
rs.setOutput( "right", answer ~= "y" ) --# Here 'answer ~= "y"' is a statement, if this statement is true it returns true, false otherwise
print( answer ~= "y" and "Ok" or "Power Off" ) --# If the answer was y then print 'Power Off', if it wasn't then print 'Ok'
The only thing it pretty much changes is making the code shorter, it works exactly as the first piece of code( if I wrote everything correctly ).
7 posts
Posted 31 July 2015 - 03:10 PM
Thanks! I thought there was something like that but I didn't know for sure.