Simple Toggle Switch

Peer support for Air Manager desktop users

Moderators: russ, Ralph

Message
Author
User avatar
Sling
Posts: 5237
Joined: Mon Sep 11, 2017 2:37 pm
Contact:

Re: Simple Toggle Switch

#11 Post by Sling »

Yep,

That’s way simpler. You may notice me giving out similar advice every time I see something like this. As you’ve figured you can bypass the if..else for these things because it’s just not necessary. It’s particularly wasteful to do

Code: Select all

function callback(var)
    If var == 1 then
        xpl_dataref_write(dataref, type, 1)
    elseif == 0 then
        xpl_dataref_write(dataref, type, 0)
    end
end
When you can simply do

Code: Select all

function callback(var)
    xpl_dataref_write(dataref, type, var)
end
Toggling the value is also another I see If..else used for a lot but again it’s not necessary. XOR works well here. Another shortened one to use when the XOR can’t be used is the simplified if function fif. so something like new = fif(pos == 1, 0, 6). Read as, if pos == 1 then make new = 0 else make new = 6.

Glad to see some thought has gone into what existing code is doing and spotting a better solution. I’m sure we can all learn new little ways to improve our code from time to time so it’s good to highlight these to the wider community. As I said previously I’ve been trying to guide folks down this route already so I hope others see this and take note of the simplicity as it’s a common block of code that’s used in the vast majority of instruments.

User avatar
jph
Posts: 2856
Joined: Fri Apr 10, 2020 12:50 pm
Location: Somewhere over the rainbow..

Re: Simple Toggle Switch

#12 Post by jph »

Hi Tony, I really appreciate that coming from you.
Thanks for the heads up on 'fif' ! I have never even heard of that before. :o Looks excellent and I will experiment.
I am not a newcomer to coding, but am definitely new to LUA. I cant help but think in other terms and syntax. I always had a penchant for using logic and Boolean bitwise operators. - and often bit masking !.
After ages searching for the equivalent of the Arduino function https://www.arduino.cc/reference/tr/lan ... itwisexor/
I eventually found the tilde ~ operator in this post.
https://stackoverflow.com/questions/597 ... xor-in-lua
I must admit, the documentation on Lua (MAIN Lua - not lua in AM directly) in general is - or to me seems - really bad, totally disjointed and confusing to me. Maybe it is just me. ? but every little helps.
I also personally try not to use - if - then - else , where possible. I am really just trying to get my head around LUA. Seeing code examples is so good as it lets me look at it in a differing way and also learn so much at the same time.
Thanks again Tony.
I will try to do my bit to try to help others, but it will definitely be limited as I have a hell of a lot to learn about both LUA and AM.
Joe.
Joe. CISSP, MSc.

Post Reply