Quantcast
Channel: Lua, if statement idiom - Stack Overflow
Viewing all articles
Browse latest Browse all 4

Answer by Nicol Bolas for Lua, if statement idiom

$
0
0

If you really want to do this in the most compact way possible, you can create a function to do it. I generally only have it take one parameter per condition, but if you absolutely need one that handles multiples, there are two ways to do it.

Option #1: Take tables:

function iff(cond, tbl1, tbl2)  if(cond) then    return unpack(tbl1)  else    return unpack(tbl2)  endend

Obviously, this requires that you always pass tables. If you only need single values, then you'd need a second version of the function. That's preferable to adding conditional logic based on types, thus slowing your code down.

Option #2: Variadic:

--Number of parameters ought to be even.--The first half are returned if the condition is true,--the second half if it is false.function iff(cond, ...)  if(cond) then    return ... --Yes, you're returning all of them, but the user shouldn't be trying to take more than the first half.  else    return select((select("#", ...)) / 2, ...)  endend

Viewing all articles
Browse latest Browse all 4

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>