Page 1 of 1
"Unexpected Symbol near if" error
Posted: Sun Sep 04, 2022 4:28 am
by Jam_Toad
Howdy!! I am kinda brand new here and I just had a really quick question.
How come this code errors? I have used this same code in other engines/frameworks and it works fine.
Code: Select all
local foo = if true then "bar" else "hello world"
Is this not a valid short circuit in Love2D?
Thank you and have a good one!
Re: "Unexpected Symbol near if" error
Posted: Sun Sep 04, 2022 12:15 pm
by BrotSagtMist
A shortcut for what?
And also, obviously your other engines use a different programming language, this code is utter gibberish.
But why it fails? You start an assignment and then open a block with a codeword leaving the assignment hanging in the air id say. Neither makes the if block any sense, "bar", like youre just throwing a string to the language without telling it what to do with it.
Youre probably looking for
local foo= true and "bar" or "hello"
That would be the common lua syntax.
Re: "Unexpected Symbol near if" error
Posted: Sun Sep 04, 2022 7:50 pm
by ReFreezed
Hello and welcome to the forums.
This is what Lua sees, and what errors the code has:
Code: Select all
local foo = -- Missing an expression after '='.
if true then
"bar" -- Invalid statement.
else
"hello world" -- Invalid statement.
end
In addition to BrotSagtMist's solution using and/or, see a
relevant page on the lua-users wiki, and the "Ternary operators" section on
this page.
Re: "Unexpected Symbol near if" error
Posted: Mon Sep 05, 2022 5:38 am
by Jam_Toad
BrotSagtMist wrote: ↑Sun Sep 04, 2022 12:15 pm
A shortcut for what?
And also, obviously your other engines use a different programming language, this code is utter gibberish.
But why it fails? You start an assignment and then open a block with a codeword leaving the assignment hanging in the air id say. Neither makes the if block any sense, "bar", like youre just throwing a string to the language without telling it what to do with it.
Youre probably looking for
local foo= true and "bar" or "hello"
That would be the common lua syntax.
My apologies, Roblox lets me do it. I realize they use a custom version of Lua called Luau, they must have added the feature.
Re: "Unexpected Symbol near if" error
Posted: Thu Sep 08, 2022 11:35 pm
by NishiyamaPedro
You can do it like this.
Code: Select all
local foo = true and "bar" or "hello world"
There are other ways to get the same result, if you are interested you can read here
http://lua-users.org/wiki/TernaryOperator