Jump to content

[TOPIC: topicViewTemplate]
[GLOBAL: userSmallPhoto]
Photo

Help understanding command
Started by Appletreeman Jan 12 2019 07:36 AM

- - - - -
3 replies to this topic

Best Answer Michael Flad , 12 January 2019 - 08:09 AM

This is a code shortcut / very similar to the ternary operator (often using the symbol ?) in other languages like C/++ etc.

 

What it does is an either/or selection/execution of code after the "and" and "or" depending on the evaluation of the expression before the "and".

 

I.e. an extended form of the code in your sample would be

 

local function _dummy_func( i )
    if i > 1 then
        return items[i-1].object.contentHeight * (i-1)
    else
        return 0
    end
end
 
items[i].object:translate(0, _dummy_func(i) )

[TOPIC CONTROLS]
[/TOPIC CONTROLS]
[modOptionsDropdown]
[/modOptionsDropdown]
[reputationFilter]
[TOPIC: post.html]
#1

Appletreeman

[GLOBAL: userInfoPane.html]
Appletreeman
  • Contributor

  • 430 posts
  • Corona SDK

Hi guys,

Quite often when looking at code I'll often see something like this...

items[i].object:translate(0, (i > 1) and items[i-1].object.contentHeight * (i-1) or 0)

What I don't get is the second half of the parameters ( from the  i>1 onwards).  Could someone help me make sense of it please.

 



[TOPIC: post.html]
#2

agramonte

[GLOBAL: userInfoPane.html]
agramonte
  • Corona Geek

  • 1,085 posts
  • Corona SDK

Somebody will probably be more eloquent than me but I use it to safeguard the code from unexpected results. The things in between the "ands" have to be true if not the item after the "or" is provided. Since nil is not true it also works with strings and nils which is very convenient (at least for me). Here is a simple example:

local thisIsNil = nil
local thisIsNot = "Not Nil"

print("Test:", (thisIsNil or thisIsNot))

 

 

Jan 12 10:59:34.540 Test: Not Nil


  • Appletreeman likes this

[TOPIC: post.html]
#3

Michael Flad

[GLOBAL: userInfoPane.html]
Michael Flad
  • Contributor

  • 225 posts
  • Corona SDK

  Best Answer

This is a code shortcut / very similar to the ternary operator (often using the symbol ?) in other languages like C/++ etc.

 

What it does is an either/or selection/execution of code after the "and" and "or" depending on the evaluation of the expression before the "and".

 

I.e. an extended form of the code in your sample would be

 

local function _dummy_func( i )
    if i > 1 then
        return items[i-1].object.contentHeight * (i-1)
    else
        return 0
    end
end
 
items[i].object:translate(0, _dummy_func(i) )

  • Appletreeman likes this

[TOPIC: post.html]
#4

Appletreeman

[GLOBAL: userInfoPane.html]
Appletreeman
  • Contributor

  • 430 posts
  • Corona SDK

@Michael Flad

That's brilliant.  A nice easy to understand explanation. Many thanks.




[topic_controls]
[/topic_controls]