Skip to content

Instantly share code, notes, and snippets.

@SoniEx2
Last active September 18, 2015 03:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SoniEx2/99882fa8d5a0740339b0 to your computer and use it in GitHub Desktop.
Save SoniEx2/99882fa8d5a0740339b0 to your computer and use it in GitHub Desktop.

The andif Idea

[I might throw this one out. Scroll down for the orif idea]

Trivial use-case

Sometimes when you're coding you end up with things like this:

if x:
    # block 1
    if y:
        # block 2
    else:
        # block 3
else:
    # block 3 (same as above)

What if you could instead do:

if x:
    # block 1
    andif y:
        # (has to be last statement in a block / must come immediately before an `else` (either implicit or explicit i.e. you can chain it))
        # block 2
    # implicit else that saves both:
    # a) bytecode size (in some rare circumstances, this can lead to faster execution)
    # b) code size (less bloat/easier to read)
else:
    # block 3

(Obviously the comments made it bigger than the other code >.> but comments != code so it's all good)

Elif?

What if you want an elif?

Doing:

if x:
    # block 1
    andif y:
        # block 2
    elif z:
        # block 3
else:
    # block 4

Would be semantically equivalent to:

if x:
    # block 1
    if y:
        # block 2
    elif z:
        # block 3
    else:
        # block 4
else:
    # block 4

The orif Idea

orif (possible operators: |if, orif, or if, ...) is a construct that allows if statements with explicit fall-through.

Trivial use-case

Take the following piece of Java:

boolean flag = false;
switch (i) {
    case 1:
        flag = true;
        // fallthrough
    case 2:
        System.out.println(flag)
        break;
    default:
        System.out.println("Unknown!")
}

In Lua (there are many ways to do it, I just picked one at random):

local flag = false
if i == 1 then
    flag = true
end
if i == 1 or i == 2 then
    print(flag)
end
if i ~= 1 and i ~= 2 then
    print "Unknown!"
end

With orif:

local flag = false
if ice == 1 then
    flag = true
orif ice == 2 then -- explicit fallthrough
    print(flag)
else -- default
    print "Unknown!"
end

Differences between orif and switch

Here's a list of pros and cons, where we compare speed, flexibility and clarity of switch and orif.

Switch:

  • +Essentially jump tables. (speed)
  • -Constant cases. (flexibility)
  • -Fallthrough-by-default (on most programming languages). (clarity)

Orif:

  • -If-else chain. (speed)
  • +Lets you test any conditions. (flexibility)
  • +Explicit fallthrough. (clarity)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment