Lua Coding Tips

From Wowpedia
Jump to: navigation, search

This is a guideline for best practices when writing Lua code.

Avoid using globals

References: WowAce coding tips

Try to use local variables whenever possible. Ideally an addon should use only a single unique global.

MyCoolAddon = {}
local value = 0

function MyCoolAddon:DoSomething()
	value = value + 1
end

For instance, the global variable a is written and read by more than a hundred addons. Lua Coding Tips 1.png

Replace getglobal

Use _G instead of the deprecated getglobal()

for i = 1, MAX_PARTY_MEMBERS do
	--local frame = getglobal("PartyMemberFrame"..i)
	local frame = _G["PartyMemberFrame"..i]
	print(frame, frame.unit)
end

Checking if something exists

Any value other than false and nil is truthy.

--if var ~= nil then
if var then
	-- do stuff
end

Similarly, use the not operator unless you want to explicitly check for false or nil.

--if var == false then
--if var == nil then
if not var then
	-- do stuff
end