self.action button example help please!

Hi, I’m looking at the button code in the Sounds Plus example in the Codea app.

I am trying to understand what this means:

if self.action then 

    self.action()

end

What is this part doing? I see self.action is set to nil in the init part…so that is nil…but what is self.action()? what do the brackets do after it? anything close to an explanation would help!!!

The action which the button performs. The self.action() means the action is changed from nil elsewhere

I still don’t understand, sorry. How can a variable (self.action) also be the name of a function (self.action())? is this allowed?

Because self.action ( a variable ) is a pointer to a function. It’s originally set to nil in Button:init but later set to point to a function in the other classes. So if it’s not nil, then it’s pointing to a function.

Ok, so, self.action starts as nil, then when the button is pressed it changes and runs the function from Main.lua…

Question: If self.action is set to nil at init, why does it still activate the if function? isn’t nil like FALSE?

Or in simpler terms

If (the function self.action does not exqual false i.e. exists) then
    run self.action
end

Maybe this will help explain what we’re talking about.


function setup()
    func="this is a string"
    print(func)
    print()
    
    func=123456
    print(func)
    print()
    
    func=func1
    print(func)
    func()
    print()
    
    func=func2
    print(func)
    func()    
end

function func1()
    print("executed func1")
end

function func2()
    print("executed func2")
end

And nil is blank or empty, not false

Thanks guys! I think I understand now. LOVE CODEA!

@david19801,
do you have Skype?

Just to correct one thing.

if var then
...
end

The condition is false if var is false or nil and true otherwise.