WoW:UI best practices: Difference between revisions

m
I appologize if this is not the proper place. UI_best_practices#Order of Operations, UI_best_practices#Lazy Coding. Corrected terminology. UI_best_practices#Short-Circuiting
(Exact same behaviour but easier to read.)
m (I appologize if this is not the proper place. UI_best_practices#Order of Operations, UI_best_practices#Lazy Coding. Corrected terminology. UI_best_practices#Short-Circuiting)
Line 71: Line 71:
  end
  end


==== Shortcut evaluation ====
==== Short-Circuiting ====


Lua uses shortcut evaluation of conditionals. This means it only evaluates enough of the condition to know for certain whether it's true or false. In the case of or, the whole condition is known to be true as soon as one operand is true. For and, the whole condition is known to be false as soon as one operand is false. You can take advantage of this to add a bit of efficiency:
Lua uses short-circuiting of conditionals. This means it only evaluates enough of the condition from left to right to know for certain whether it's true or false. In the case of "or", the whole condition is known to be true as soon as one operand is true. For "and", the whole condition is known to be false as soon as one operand is false. You can take advantage of this to add a bit of efficiency:


  if Fast() or Slow() then
  if Fast() or Slow() then
Line 82: Line 82:
     DoStuff()
     DoStuff()
  end
  end
==== Order of Operations ====
Lua, like all other programming languages, executes expressions from left to right starting from the innermost parenthesis to the outermost. This allows for un-nesting of IF blocks.
-- This:
if a and b then
    if c or d then
        DoStuff()
    end
end
-- Can be written as:
-- As described in the previous section, if "a" or "b" are false, then DoStuff() will never execute
-- If "a" and "b" are true and "c" or "d" are true, then DoStuff() will run.
if a and b and (c or d) then -- same as "a and ((b and c) or (b and d))" (yes, the distributive property works here too)
    DoStuff()
end
==== Lazy Coding ====
You can utilize the Short-Circuiting functionality to make sure a variable has a value before comparing it to a literal:
if foo[bar] == 5 then -- might throw "attempting to index field ? a nil value"
    DoStuff()
end
if foo[bar] and foo[bar] == 5 then -- will not throw an error
    DoStuff()
end
You can also "cheat" if all you want to do is make sure a variable has a value other than nil or false:
-- This:
if foo then
    print(foo)
elseif bar then
    print(bar)
else
    print("nothing to print")
end
-- Can be written as:
print(foo or bar or "nothing to print")


=== Minimize use of throw-away tables ===
=== Minimize use of throw-away tables ===
Line 113: Line 153:
     end
     end
  </OnEvent>
  </OnEvent>
Note: Lua code must be inserted inside event handlers or it will never run.


==== XML calling Lua function ====
==== XML calling Lua function ====
Anonymous user