SelDraken
(SelDraken)
August 31, 2023, 11:43am
#1
I once used to code in javascript, but its been so long that I am not sure about a certain line I am trying to convert.
If in javascript I have the line
x === 1 ? 1 : 2
Isn’t that saying
if x is strictly equivalent to 1 then return the value of 1
if its not, return the value of 2
and if that is correct, in lua I could do
if x == 1 then return 1 else return 2
but is there any way in lua to do the == ? : statement
Thanks
1 Like
NoxhazeI
(Johnathan)
August 31, 2023, 11:53am
#2
You are correct till the javascript part. Not in lua. For that do:
local x = 1
local y = x == 1 and 1 or 2 -- set y to 1 if x is 1 else to 2.
If statement wise:
local x = 1
local y
if x == 1 then
y = 1
else
y = 2
end
I do understand that it makes absolutely no sense, but thats just how its designed.
2 Likes
SelDraken
(SelDraken)
August 31, 2023, 11:56am
#3
Ok, so the ‘and’ and ‘or’ in lua is the same as the ‘?’ and ‘:’ in javascript
Thanks
1 Like
Blockzez
(Blockzez)
August 31, 2023, 12:08pm
#4
In Luau, you could use if x then y else z
as that’s preferred over the idiom x and y or z
: Syntax - Luau
That’s because Lua is designed to be minimal.
No, a and b or c
in Lua(u) will behave differently to what you expect if b
, converted to boolean, is false
.
3 Likes
NoxhazeI
(Johnathan)
August 31, 2023, 12:10pm
#5
Well kind of. As @Blockzez stated. Also I didnt know that. But I would still prefer using the old method as both do the same thing just in a different way.
And yes, I know that. Been developing in it for quite some time.
SelDraken
(SelDraken)
August 31, 2023, 12:23pm
#6
I was converting a function on easing
function easeOutExpo(x: number): number {
return x === 1 ? 1 : 1 - Math.pow(2, -10 * x);
}
So what I ended up doing was this
function easeOutExpo(x)
if x == 1 then return 1 else return 1 - math.pow(2, -10 * x) end
end
I think that should be the best conversion based on what you both have said.
NoxhazeI
(Johnathan)
September 2, 2023, 5:07am
#7
Yes thats true! Another way is:
function easeOutExpo(x)
return x == 1 and 1 or 1 - math.pow(2,-10*x)
end
system
(system)
Closed
September 16, 2023, 5:08am
#8
This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.