Why is the else statement is not allowed to have a then or other conditions?
Is it because it is the final condition within the else-if conditions it represents?
I am struggling to understand this concept since I'm a beginner who just learned about variables.
I'm asking this because I received an error with my else statement in the code:
message = 0
condition = 30
if condition <=10
message = “try harder”
elseif
condition <=20 then
message = "Almost learning"
else
condition = <=30 **—This is the line where I get the error message**
message = "Now you’re getting it"
end
print(message)
Would appreciate someone breaking down in laymen terms, why else is not allowed to have < or > or then or other conditions.
else condition = <= 30
(which is the way your code was originally formatted) would be a very unusual feature in a language.
The whole point of else on its own is to execute if none of the other conditions were true. So a condition on the else is absolutely useless.
The Programming in Lua book if statement shows the normal usage:
if op == "+" then
r = a + b
elseif op == "-" then
r = a - b
elseif op == "*" then
r = a*b
elseif op == "/" then
r = a/b
else
error("invalid operation")
end
However, your actual code (when formatted correctly) ends up looking like:
else
condition = <=30
which is correct in terms of the else but unfortunately makes the next line a statement. And this statement is very much incorrect syntax.
Now it may be that you meant to assign 30 to condition but, based on your other lines (that sort of match this as a condition), I suspect not. So it's probably best just to remove that line totally.
Related
I use Lua in computercraft to automate the mining. But, my turtle whose program worked very well before, stops if it meets a lava/flowing_lava/water/flowing_water source.
Inside my program, I have a lot of function to manage, for example, the fuel management, the tunnel, the collision with gravel, and .. the detection if the turtle meets a "block".
If the block is just an air block, the turtle continues to advance, elseif the block isn't an air block, the turtle digs this block and doesn't move forward if there is still a block in front of her.
The problem? The four sources which I quoted previously are considered as blocks, and the turtle can't move forward.
I try to fix this problem with multi-condition into the if, but it's doesn't work, the turtle moves forward and dig in any direction.
So I think it's because my way of creating the if isn't good, maybe the syntax (for concatenating many or into () ).
How to solve this issue?
function blockDetection(position, justDetection)
success, detectionBlock = nil
block_name = ""
if position == "right" then
turtle.turnRight()
success, detectionBlock = turtle.inspect()
turtle.turnLeft()
if success then
block_name = detectionBlock.name
if justDetection == true and detectionBlock.name == "minecraft:air" then
block_name = true
elseif justDetection == true and detectionBlock.name ~= "minecraft:air" then
block_name = false
else
end
end
end
end
I think your problem is that you forgot to return block_name. If you omit the return statement, you implicitly return 0 arguments, so trying to access any would give nil values. For example
if blockDetection (position,justDetetcion) then --[[something]] end, would never execute the then-end block, since nil is considered false.
You should also one more thing you should change in your code:
You shouldn't use x==true. If x is a boolean, then if x==true then ... is equivalent to if x then ....
So, your code should look a like this:
function blockDetection(position, justDetection)
success, detectionBlock = nil
block_name = ""
if position == "right" then
turtle.turnRight()
success, detectionBlock = turtle.inspect()
turtle.turnLeft()
if success then
block_name = detectionBlock.name
if justDetection and detectionBlock.name == "minecraft:air" then
block_name = true
elseif justDetection and detectionBlock.name ~= "minecraft:air" then
block_name = false
else
end
end
end
return block_name
end
My current ruby commandline app uses STDIN.ready?. This permits me to capture complex keys such as Meta keys, Function keys, shifted-function keys etc.
I am not finding anything similar in Crystal.
While searching I found STDIN.raw &.read_char.
According to the docs, this should return a nil when there is nothing to read. However, I am not getting a nil. It seems to wait for the next key. The ruby code had a $stdin.getc.
My logic basically keeps reading STDIN as long as it is ready and accumulating key codes. The moment ready? returns false, the key is evaluated.
The logic NOW is:
c = STDIN.raw &.read_char
if c == '\e' # escape char
loop do
k = STDIN.raw &.read_char
if k
# accumulate k into a string
else
# evaluate string and return
end
end #loop
end
# rest of code if not escape.
Currently the else condition does not execute, so I am stuck in the if part. I don't know when to stop reading keys.
Previously, in ruby I had the second getc inside a if STDIN.ready?.
Earlier in ruby:
if c == '\e'
loop
if STDIN.ready?
k = STDIN.getc
accumulate in string
else
evaluation string and return code
end
end
end
EDIT: for me the correct answer lies in the link to 2048.cr suggested below in a comment.
This is not an answer, it is just a workaround if no correct answers here.
def handle_second_key(buffer)
loop do
input = STDIN.raw &.read_char
buffer << input if input
if buffer.size == 2
if buffer[0] == '\e' && buffer[1] == 'q'
puts "Right combination #{buffer[0].dump} + #{buffer[1].dump}"
exit
else
puts "Wrong combination: #{buffer[0].dump} + #{buffer[1].dump}"
break
end
end
end
end
buffer = [] of Char
loop do
input = STDIN.raw &.read_char
buffer << input if input
if buffer[0] == '\e'
handle_second_key(buffer)
buffer.clear
else
buffer.clear if buffer.size > 0
end
end
I'm trying to determine if it's between the hours of 12 am and 1 am. Here is my if statement:
If InStr(Time,"12") AND InStr(Time,"AM") Then
' Do something
Else
' Do something else
End If
The problem is that this statement evaluates to false, even if both of the conditions are true. I know this because I have tried a nested if like this
If InStr(Time,"12") Then
If InStr(Time,"AM") Then
' Do something
...
And that works. This also works
If InStr(Time,"12")<>0 AND InStr(Time,"AM")<>0 Then
' Do something
...
But if it works as a nested if, why can't I test both of the nested if conditions in a single if statement?
I replaced the InStr function calls with the values that they return
If 1 AND 10 Then
' Do something
Else
' Do something else
End If
And the same thing happened: the if statement evaluated as false and the "Do something else" commands were executed instead. But when I nested the second condition as another if statement inside the first if statement, the "Do something" commands were executed.
Why is that and is there any way to do this without the <>0 and without nesting?
If Time() >= TimeValue("12:00:00") AND Time() <= TimeValue("23:59:59") then
'Do Something
ElseIf Time() >= TimeValue("00:00:00") AND Time() <= TimeValue("01:00:00") then
'Do the same
Else
'Do something different
End If
This should work :)
The problem you observed is caused by the fact that VBScript uses the same operators for boolean and bit operations, depending on the data type of the operands. The InStr function returns a numeric value unless one of the strings is Null, so the operation becomes a bitwise comparison instead of a boolean comparison, as JosefZ pointed out. The behavior is documented:
The And operator also performs a bitwise comparison of identically positioned bits in two numeric expressions and sets the corresponding bit in result [...]
Demonstration:
>>> WScript.Echo "" & (True And True)
True
>>> WScript.Echo "" & (6 And 1) '0b0110 && 0b0001 ⇒ 0b0000
0
>>> WScript.Echo "" & (6 And 2) '0b0110 && 0b0010 ⇒ 0b0010
2
To enforce a boolean comparison you need to use InStr(...) > 0 or CBool(InStr(...)) (both of which evaluate to a boolean result) instead of just InStr(...) (which evaluates to a numeric result).
Date and Time are stored as number of days, where midnight is 0.0, and 1 am is 1/24 :
If Time <= 1/24 Then ' or If Time <= #1am# Then
When you using Time() function and if result like that 10:12:12 AM in this way Instr will result Ture because Instr by default use vbbinarycompare looking For any 12in binary format in 10:12:12 AM and there is sec and min 12 so it will Return True .
just try this :
myHour=replace(Time,Right(Time,9),"") 'get only the hour from time
myAMPM=replace(Time,Time,Right(Time,2)) 'get only AM or PM from time
If InStr(1,myHour,12,1) > 0 AND InStr(1,myAMPM,"AM",1) > 0 Then
wscript.echo "True"
Else
wscript.echo "False"
End If
Excuse me for the use of the term "component", there probably is a better term to use in such context.
But moving on to my question, I want to use the else statement to execute a statement block based on the truth of the test statement. Here is the test statement I tried using:
else:
if ((reply != a) && (reply != c) && (reply =! e)):
I'm getting a syntax error, and the carrot is pointing at the first set of ampersands. I'm assuming now that I might be improperly using '&&'.
With this statement, my goal is to execute the statement block only if the test statement is true, meaning further, that 'reply' must not be equal to a, c, or e.
I know that I can use nested if's under the else statement, but I'm hoping StackExchange knows a better way. Thank you.
parenthesis check :
if (((reply != a) && (reply != c)) && (reply =! e))
The "single line if statement" exists in C# and VB.NET as in many other programming and script languages in the following format
lunchLocation = (dayOfTheWeek == "Tuesday") ? "Fuddruckers" : "Food Court";
does anyone know if there is even in VBScript and what's the extact syntax?
The conditional ternary operator doesn't exist out of the box, but it's pretty easy to create your own version in VBScript:
Function IIf(bClause, sTrue, sFalse)
If CBool(bClause) Then
IIf = sTrue
Else
IIf = sFalse
End If
End Function
You can then use this, as per your example:
lunchLocation = IIf(dayOfTheWeek = "Tuesday", "Fuddruckers", "Food Court")
The advantage of this over using a single line If/Then/Else is that it can be directly concatenated with other strings. Using If/Then/Else on a single line must be the only statement on that line.
There is no error checking on this, and the function expects a well formed expression that can be evaluated to a boolean passed in as the clause. For a more complicated and comprehensive answer see below. Hopefully this simple response neatly demonstrates the logic behind the answer though.
It's also worth noting that unlike a real ternary operator, both the sTrue and sFalse parameters will be evaluated regardless of the value of bClause. This is fine if you use it with strings as in the question, but be very careful if you pass in functions as the second and third parameters!
VBScript does not have any ternary operator.
A close solution in a single line and without using a user defined function, pure VBScript:
If dayOfTheWeek = "Tuesday" Then lunchLocation = "Fuddruckers" Else lunchLocation = "Food Court"
BTW, you can use JScript in Classic ASP if ternary opertor is so important to you.
edited 2017/01/28 to adapt to some of the non boolean condition arguments
Note: If all you need is to select an string based on an boolean value, please, use the code in the Polinominal's answer. It is simpler and faster than the code in this answer.
For a simple but more "flexible" solution, this code (the original code in this answer) should handle the usual basic scenarios
Function IIf( Expression, TruePart, FalsePart)
Dim bExpression
bExpression = False
On Error Resume Next
bExpression = CBool( Expression )
On Error Goto 0
If bExpression Then
If IsObject(TruePart) Then
Set IIf = TruePart
Else
IIf = TruePart
End If
Else
If IsObject(FalsePart) Then
Set IIf = FalsePart
Else
IIf = FalsePart
End If
End If
End Function
If uses the Cbool function to try to convert the passed Expression argument to a boolean, and accepts any type of value in the TrueValue and FalseValue arguments. For general usage this is fast, safe and fully complies to documented VBScript behaviour.
The only "problem" with this code is that the behaviour of the CBool is not fully "intuitive" for some data types, at least for those of us that constantly change between vbscript and javascript. While numeric values are coherent (a 0 is a False and any other numeric value is a True), non numeric types generate a runtime error (in previous code handled as false), except if it is a string with numeric content or that can be interpreted as true or false value in english or in the OS locale.
If you need it, a VBScript version "equivalent" to the ? javascript ternary operator is
Function IIf( Expression, TruePart, FalsePart )
Dim vType, bExpression
vType = VarType( Expression )
Select Case vType
Case vbBoolean : bExpression = Expression
Case vbString : bExpression = Len( Expression ) > 0
Case vbEmpty, vbNull, vbError : bExpression = False
Case vbObject : bExpression = Not (Expression Is Nothing)
Case vbDate, vbDataObject : bExpression = True
Case Else
If vType > 8192 Then
bExpression = True
Else
bExpression = False
On Error Resume Next
bExpression = CBool( Expression )
On Error Goto 0
End If
End Select
If bExpression Then
If IsObject( TruePart ) Then
Set IIf = TruePart
Else
IIf = TruePart
End If
Else
If IsObject( FalsePart ) Then
Set IIf = FalsePart
Else
IIf = FalsePart
End If
End If
End Function
BUT independently of the version used, be careful, you are calling a function, not using a ternary operator. Any code, or function call you put in TruePart of FalsePart WILL BE EXECUTED independently of the value of the condition. So this code
value = IIf( 2 > 3 , DoSomething(), DontDoSomething() )
WILL EXECUTE the two functions. Only the correct value will be returned to value var.
There's a weird trick possible (hi, Python!) for exact one-liner:
lunchLocation = array("Food Court", "Fuddruckers")(-(dayOfTheWeek = "Tuesday"))
The "magic" works because of a boolean operation specifics in VBScript.
True is actually -1 and False is 0, therefore we can use it as an index for array (just get rid of a minus). Then the first item of array will be a value for False condition and second item for True.
related to #MC_ND answer:
to execute only one function, you can do something like that:
If VarType(TruePart) = vbString and InStr(1,TruePart,"function:") = 1 then
IIf = GetRef(Mid(TruePart,10))()
Else
IIf = TruePart
End If
the same for the FalsePart, and call IIf() it like that:
value = IIf( 2 > 3 , "function:DoSomething", "function:DontDoSomething" )
and will call DoSomething() or DontDoSomething()