Help with Conversion of?

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

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

Ok, so the ‘and’ and ‘or’ in lua is the same as the ‘?’ and ‘:’ in javascript

Thanks

1 Like

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

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.

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.

Yes thats true! Another way is:

function easeOutExpo(x)
	return x == 1 and 1 or 1 - math.pow(2,-10*x)
end

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.