Quantcast Coding Idioms - WoWInterface
Thread Tools Display Modes
02-28-06, 12:19 AM   #1
Silversage
A Flamescale Wyrmkin
AddOn Author - Click to view addons
Join Date: Nov 2005
Posts: 132
Coding Idioms

After coding in Lua for a few months, I've started to develop a few idioms that simplify my code. They are 'idioms' in the sense that the first time you see them, you have to puzzle out what's going on, but afterward, it becomes a short, easy-to-read way to express a concept.

Here are a couple of my idioms. If you have some, I'd like to hear them.

SAVED_VAR = SAVED_VAR or {}; --init if needed

Since Lua uses 'short-cut' evaluation of logical or, if SAVED_VAR was non-nil, and not equal to false, then it will end up being initialized to {}. One application would be saved variables in the VARIABLES_LOADED event handler.

Another use is providing a default value for a procedure that usually returns a value, but might return nil.
local string = SomeFunctionThatMightReturnNil(blah, blah) or "";

A 3rd application would be in situations where you might be counting stuff, but nil really means zero. Let's say you were counting the number of times you saw a certain target, and you have a table to keep track of all the various targets.
local name = UnitName('target');
timesSeenByName[name] = 1 + (timesSeenByName[name] or 0);

I was also missing Java's (and C's) ternary, if-then expression operator. But since Lua short-cuts and as well as or, you can use this to create your own ternary operator.
boolean and ifTrueValue or ifFalseValue
will evaluate to ifFalseValue if boolean is either nil or false. Otherwise, it evaluates to ifTrueValue.

local nameOfTarget = UnitExists('target') and UnitName('target') or '<no target>';

Anyway, I showed you mine. Now you show me yours.
  Reply With Quote

WoWInterface » Developer Discussions » General Authoring Discussion » Coding Idioms

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off