Jump to content

Quicker way of writing if-statements


tosfera

Recommended Posts

Posted

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:

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

You can also do that.

Hmm, you just solved and also ruined my suggestion. Awesome job. :lol::oops:

  • MTA Team
Posted

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)

  • 2 weeks later...
Posted
local text = ( 5 > 4 and "I'm bigger!" or "I'm smaller..." ) 
outputChatBox ( text ) 

You can also do that.

Keep in mind that this method is not identical to a?b:c and has one caveat:

  
local result = A and B or C 
  

If B evalutes to false, then C will be assigned.

  • 2 weeks later...
Posted
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

  • 5 months later...
  • Recently Browsing   0 members

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