WoWInterface

WoWInterface (https://www.wowinterface.com/forums/index.php)
-   General Authoring Discussion (https://www.wowinterface.com/forums/forumdisplay.php?f=20)
-   -   Coding Idioms (https://www.wowinterface.com/forums/showthread.php?t=3886)

Silversage 02-28-06 12:19 AM

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.


All times are GMT -6. The time now is 12:29 PM.

vBulletin © 2024, Jelsoft Enterprises Ltd
© 2004 - 2022 MMOUI