Jump to content

Quicker way of writing if-statements


tosfera

Recommended Posts

Hey guys,

Since I'm working with alot of programming languages at a time, and alot of scripting languages too. I sometimes walk against problems which makes me,,, quite tired. Let's take the if-statement, for a simple if-statement you have to use atleast 5 lines. Quite a few if you ask me sometimes haha. Everyone knows how the if-statement works, if you don't take a look:

if ( condition ) then 
     -- do something 
else 
     -- do something 
end 

Now, in alot of languages there are alot of easier ways to write this. Not sure if LUA already has this but I'd get some errors while trying it in a script. So, the setup of the if-statement is like this:

condition ? -- do something : -- do something else 

For example;

if ( 5 > 4 ) then 
    outputDebugString ( "I'm bigger!" ); 
else 
    outputDebugString ( "I'm not bigger..." ); 
end 

would turn into;

5 > 4 ? outputDebugString ( "I'm bigger!" ); : outputDebugString ( "I'm not bigger..." ); 

It would be easy for simple and small checks, like single checks of guiGetText, vehicleLights, lock systems, bool's etc. So, let me know what you guys think of it. And YES, I am lazy. :roll::lol:

Link to comment

or just

local text = (5 > 4) and "I'm bigger!" or "I'm smaller!" 

paran's around the entire thing is unneeded, because what else will it set? paran's aren't needed around "5>4" but it makes code appear more obvious.

What if you wanted the second value to the "more-than" operand to be evaluated to "I'm bigger!" (even though it wouldn't work)

Link to comment
  • 2 weeks later...
  • 2 weeks later...
Functional-if

One can also write if as a function:

function fif(condition, if_true, if_false)

if condition then return if_true else return if_false end

end

print( fif(condition, a, b) )

but this does not have the advantage of short-circuiting unless the conditions are expressed as anonymous closures for delayed evaluation:

function fif(condition, if_true, if_false)

if condition then return if_true() else return if_false() end

end

local x = fif(condition, function() return a end, function() return b end)

print(x) --> false

Link to comment
  • 5 months later...
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...