Converting Luau to Lua: If-then-else

When converting Luau to vanilla Lua, how could the if-then-else expression be represented?

Like, is this a perfect representation for it?

if not a then b else c <-
-> (a ~= nil and a) and b or c

In most cases, as

not a and b or c

If b is a falsy value, this won’t work. Given a = false, b = false, c = “c”, not a and b will evaluate to not false and false or "c" → true and false or "c" → false or "c" → "c", while you’d expect the statement to return false from b.
In such cases, you’d have to write proper logic, e.g.

local val = c
if not a then
    val = b
end

Alternatively, just use if not a then b else c. I’m uncertain why you’d want to convert luau to lua, but if you’re staying in roblox, there’s no need to do this.

Writing proper logic to it simply feels bad. The reason if-then-else expressions exist is to literally avoid more lines than needed

and Luau isn’t exclusive to Roblox anymore, sometime you’ll find yourself having to remove luau-only things, such as interpolated strings and types of it.

Luau is great, but it’s slow. It’s cool having alot of new cool features, but that’s a fact. Backporting a Luau project to other Lua runtimes (specifically, LuaJIT) when deploying your project can be beneficious for perfomance improvements.

Write it on Luau, convert to LuaJIT later.

If line count is what you’re worried about, you can simply

({[true] = b, [false] = c})[not a]

Additionally, this allows you to flex your lua knowledge.

If you want to use LuaJIT, it might be better to just use the proper logic version. I doubt LuaJIT will optimize away my newest example. If you happen to know that b will never be a falsy value, you can do the normal not a and b or c version.

2 Likes

Not sure what you mean by flex your lua knowledge, but i don’t think a normal ternary-like operation would be the best to transpile if a then b else c into.

The reason if-expressions exist is to avoid bugs that were caused by normal ternary-like operations. not x and y or z whereas x mostly caused bugs by the fact that it could also be nil.

Syntax - Luau (luau-lang.org)

I know the reason why if a then b else c exists.
If you can ensure that b is never falsy, then a simple a and b or c suffices.
If you cannot ensure this, writing out the formal logic is your best choice.
The only real alternative is using a table lookup, as I’ve described in my comment earlier. This’d be a one-lines, although unreadable and likely many times more expensive than using the formal logic.

1 Like