This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
Engineer's profile picture

Shorter if statement

Started by Engineer, 03 March 2013 - 10:35 AM
Engineer #1
Posted 03 March 2013 - 11:35 AM
Hi,

(Question about LUA, dont worry if you dont know java ;P)

I am learning Java now and there you have two kinds of if statements, the one that is printable:

    In Java:
        System.out.println( ( random_var > 1)? "Heey guys" : "See you later guys" );

Basicly it questions if random_var is bigger than one and if this is true then it prints "Heey guys" and if it is false then it prints "See you later guys".

You also have the other if statement, and this one is similair to LUA.

   in LUA:
        if random_var == 5 then
                    print("Hello World!")
        else
                    print("Bye World!")
        end

   in Java:
       if (random_var == 5){
            System.out.println("Hello world!");
       } else{
            System.out.println("Bye world!");
       }

Now my question is:
Is the first if statement also in LUA?

Thanks :)/>
Eric #2
Posted 03 March 2013 - 11:55 AM

print(random_var == 5 and "Hello World!" or "Bye World!")
theoriginalbit #3
Posted 03 March 2013 - 01:44 PM
I am learning Java now and there you have two kinds of if statements, the one that is printable:

	In Java:
		System.out.println( ( random_var > 1)? "Heey guys" : "See you later guys" );
just an FYI there are not 2 kinds of if statements. there is if:

if ( <condiftion> ) {
  <if true>
}
else {
  <if false>
}
and there is what is called a ternary operator:

<condition> ? <if true> : <if false>

A ternary operator is far more than a 'printable' if statement. it can be used in assignment statements too.
Where in an if statement you might do this

if ( player.collided ) {
  player.location.x = world.teleporter.location.x
}
else {
  player.location.x = player.location.prevX
}
it can also use a ternary operator by using the following

player.location.x = ( player.collided ? world.teleporter.location.x : player.location.prevX )

So really a ternary operator is a shortened form of an if else statement.

Now as Eric posted a ternary in Lua can be done with

<condition> and <if true> or <if false>

now there is just another thing I would like to point out, since i have seen people do it before. lets say we have this code

local args = { ... } -- runtime arg that is the 'depth' the user wants
local depth
if args[1] ~= nil then
  depth = args[1]
else
  depth = 5
end
this would set a default depth if one is not supplied. so now we make it nicer by using Lua's form of the ternary

local args = { ... }
local depth = args[1] ~= nil and args[1] or 5
so this looks about right and done. well we can go a step further, obviously we are saying if a depth has been supplied use it, or make it 5. so that can be simplified to

local args = { ... }
local depth = args[1] or 5

Hope this helped explain a few things. :)/>
Engineer #4
Posted 03 March 2013 - 02:05 PM
I am learning Java now and there you have two kinds of if statements, the one that is printable:

	In Java:
		System.out.println( ( random_var > 1)? "Heey guys" : "See you later guys" );
just an FYI there are not 2 kinds of if statements. there is if:

if ( <condiftion> ) {
  <if true>
}
else {
  <if false>
}
and there is what is called a ternary operator:

<condition> ? <if true> : <if false>

A ternary operator is far more than a 'printable' if statement. it can be used in assignment statements too.
Where in an if statement you might do this

if ( player.collided ) {
  player.location.x = world.teleporter.location.x
}
else {
  player.location.x = player.location.prevX
}
it can also use a ternary operator by using the following

player.location.x = ( player.collided ? world.teleporter.location.x : player.location.prevX )

So really a ternary operator is a shortened form of an if else statement.

Now as Eric posted a ternary in Lua can be done with

<condition> and <if true> or <if false>

now there is just another thing I would like to point out, since i have seen people do it before. lets say we have this code

local args = { ... } -- runtime arg that is the 'depth' the user wants
local depth
if args[1] ~= nil then
  depth = args[1]
else
  depth = 5
end
this would set a default depth if one is not supplied. so now we make it nicer by using Lua's form of the ternary

local args = { ... }
local depth = args[1] ~= nil and args[1] or 5
so this looks about right and done. well we can go a step further, obviously we are saying if a depth has been supplied use it, or make it 5. so that can be simplified to

local args = { ... }
local depth = args[1] or 5

Hope this helped explain a few things. :)/>

Thanks alot. I didnt know it was a ternary operator, but like you said it is the same concept. Its also for me a reminder for what it actually does, so I prefer to call it a shortened if-statement :D/>

Thank you TheOriginalBit and Eric for the great response.
Now I can simplify my Java-to-LUA thoughts :)/>
LancerX #5
Posted 05 March 2013 - 05:28 AM
Implementing your own ternary() function is pretty straightforward and a nice addition to your utils API. You do have your own utils toolkit, right?


-- ternary, because even Java has one
--	cond: condition to eval
--	tVal: return val if cond == true
--	fVal: return val if cond == false
--	returns tVal or fVal
function ternary(cond, tVal, fVal)
	if cond then
	  return tVal
	else
	  return fVal
	end
end

-- example:
item = ternary(isOpenSlot(slot), itemToStock(), nil)

remiX #6
Posted 05 March 2013 - 05:43 AM
Implementing your own ternary() function is pretty straightforward and a nice addition to your utils API. You do have your own utils toolkit, right?


-- ternary, because even Java has one
--	cond: condition to eval
--	tVal: return val if cond == true
--	fVal: return val if cond == false
--	returns tVal or fVal
function ternary(cond, tVal, fVal)
	if cond then
	  return tVal
	else
	  return fVal
	end
end

-- example:
item = ternary(isOpenSlot(slot), itemToStock(), nil)


function ternary(cond, tVal, fVal)
	return cond and tVal or fVal
end
LancerX #7
Posted 05 March 2013 - 06:11 AM
@remiX: Cool, I just started with Lua/CCraft this weekend, I'm still picking up a lot of the idioms.
remiX #8
Posted 05 March 2013 - 06:57 AM
@remiX: Cool, I just started with Lua/CCraft this weekend, I'm still picking up a lot of the idioms.

Heh :)/>

You don't really need to make a function, because you just need to do this:
item = isOpenSlot(slot) and itemToStock() or nil
It does the same thing, but no need for a function then
shiphorns #9
Posted 05 March 2013 - 07:28 AM
Implementing your own ternary() function is pretty straightforward and a nice addition to your utils API. You do have your own utils toolkit, right?


-- ternary, because even Java has one
--	cond: condition to eval
--	tVal: return val if cond == true
--	fVal: return val if cond == false
--	returns tVal or fVal
function ternary(cond, tVal, fVal)
	if cond then
	  return tVal
	else
	  return fVal
	end
end

-- example:
item = ternary(isOpenSlot(slot), itemToStock(), nil)


function ternary(cond, tVal, fVal)
	return cond and tVal or fVal
end

Yeah, that's great if you just want to switch between 2 return r-values, but I'd just like to point out to the OP that this falls well short of the Java or C++ ternary operator's flexibility where any of the 3 arguments can be full expressions, such as assignments, function calls, etc., even multiple statements separated with the comma operator (though that would typically be bad style).

For more reading and options to work around not having the Ternary operator, see: http://lua-users.org...TernaryOperator
Lyqyd #10
Posted 05 March 2013 - 08:57 AM
Implementing your own ternary() function is pretty straightforward and a nice addition to your utils API. You do have your own utils toolkit, right?


-- ternary, because even Java has one
--	cond: condition to eval
--	tVal: return val if cond == true
--	fVal: return val if cond == false
--	returns tVal or fVal
function ternary(cond, tVal, fVal)
	if cond then
	  return tVal
	else
	  return fVal
	end
end

-- example:
item = ternary(isOpenSlot(slot), itemToStock(), nil)


This is not helpful, since it is equivalent to Lua's `exp and exp or exp` construct, except less powerful. It also incurs the overhead of a function call unnecessarily.
shiphorns #11
Posted 05 March 2013 - 10:28 AM
This is not helpful, since it is equivalent to Lua's `exp and exp or exp` construct, except less powerful. It also incurs the overhead of a function call unnecessarily.

Well, it does work more like a ternary operator than the and/or construct. Though widely used, the cond and value1 or value2 construct does not evaluate how you might expect for the case where cond1 is true and value1 is false; the whole expression will evaluate to value2, not value1 as you'd expect with a ternary operator or its equivalent if-then-else form. Try this in the lua prompt:


>print(true and false or 5)

You'll get 5, not false as you would from true?false:5; in a C language.
Lyqyd #12
Posted 05 March 2013 - 11:03 AM
This is not helpful, since it is equivalent to Lua's `exp and exp or exp` construct, except less powerful. It also incurs the overhead of a function call unnecessarily.

Well, it does work more like a ternary operator than the and/or construct. Though widely used, the cond and value1 or value2 construct does not evaluate how you might expect for the case where cond1 is true and value1 is false; the whole expression will evaluate to value2, not value1 as you'd expect with a ternary operator or its equivalent if-then-else form. Try this in the lua prompt:


>print(true and false or 5)

You'll get 5, not false as you would from true?false:5; in a C language.

True, though if you plan on using false (or nil) as one of your return values (or expect that it may appear as one), you can easily re-order the statement and invert the conditional. There are always times when Lua's ternary-like construct is not appropriate. It is an important caveat to know, though not one that is likely to be commonly encountered, methinks.
LancerX #13
Posted 05 March 2013 - 03:06 PM
As someone who is trying to pick up Lua and CC as quickly as possible, the faux-ternary approach was irritating when I had to stop and think through the booleans everytime I wanted to use it. It was easier for me to stay in the flow by having an explicit function that behaved like the rest of the world's ternaries ;)/>

I'm sure at some point I'll throw the crutch away, but for now it's staying :)/>
3ydney #14
Posted 05 March 2013 - 07:57 PM
No the 'if' statement is in lua. You build lua. You dont make an OS in lua but instead you build LUA. The mod is written is Java that can then build lua. It is a little hard to understand. For example I can make an 'os' in lua but its called building lua. Lua is designed so you can add/build on top of it. Lua is the OS its self. You could run lua on a computer provided you coded the assembley for it. Im not going to so please dont ask. I know how to code Java really well so just ask if you need a hand but it seems others have awnsered your question.