Common Lua shortcuts

From Wowpedia
Jump to: navigation, search

This article covers several syntactic features of Lua that are commonly used in addon code.

Logical short-cut evaluation

When evaluating the results of boolean operators and and or, Lua only evaluates the right-hand operand if necessary. This makes it possible to provide default values to nil or false expressions, or implement something resembling the C/C++ ternary expression (A?B:C):

For instance:

MySVTable = MySVTable or {}
print(UnitExists("target") and "You have a target" or "You don't have a target")

A notable limitation of using short-cut evaluation as a ternary expression is that the middle expression must not be false/nil. (After all, there is no actual ternary expression; you are simply chaining boolean expressions and must still follow their rules of precedence.)

function isFrameShown(frame, checkParentFrames)
 -- The expression below returns the wrong value if frame's parent is hidden.
 return checkParentFrames and frame:IsVisible() or frame:IsShown()

If you find yourself writing code of the style A and B or C, you may need to rewrite it to ensure that B can never be false or nil.

Colon syntax for defining methods

The colon syntax is used for defining methods -- functions that have an implicit first parameter self. The following function definitions are equivalent:

t = {}
function t:foo(bar) end
function, bar) end

When you call a function using the colon syntax, you implicitly supply the table left of the colon as the first argument to the function. The following two function calls are equivalent:

t:foo("baz"), "baz")

This notation is frequently used to emulate something resembling objects.

The global environment table

The global environment table _G is defined in most function environments. You can look up global variables by using their names as a key in this table. For example:

-- Suppose MyBar1, MyBar2, MyBar3 are global variables (Frames created in XML, for example)
for i=1, 3 do
 _G["MyBar" .. i]:Show()

The getglobal("name") function used to do the same thing, but has now been deprecated and removed.