Lua: Config-table defaults
While rewriting rothar’s new WoW AddOn RingMod which creates circular statusbars to fit in a small library, I discovered a good technique to provide default values for custom config-tables.
Let’s assume we got a custom table which holds some options like:
local config = {
width = 30,
height = 20,
enableMouse = false,
}
Normally one would now check in his/her addon whether the values are actually set and provide default values, like:
frame:SetWidth(config.width or 1)
frame:SetHeight(config.height or 1)
frame:EnableMouse(config.enableMouse or true)
This of course causes a lot additional code to add into the function and it gets confusing very quick. And do you notice something? Even if someone sets config.enableMouse to ‘false’, our default entry still switches to ‘true’, because the statement “ ‘false’ or ‘true’ “ results in ‘true’ every time.
A cleaner and easier way would be to use Lua’s powerful metatables. We define a defaults-table at the beginning and then use metatables’ __index-entry to point at it. This means, every time an entry in our config-table is ‘nil’, Lua fetches the value from the defaults. Useful, eh?
— Our defaults values
local defaults = {__index = {
height = 1,
width = 1,
enableMouse = false,
}}
— Now add metatable magic to our config-table from above
setmetatable(config, defaults)
— And from this time on we can write:
frame:SetWidth(config.width)
frame:SetHeight(config.height)
frame:EnableMouse(config.enableMouse)
By the way, my library can be found under LibRingBars-1.0 @ github.
07:22 PM | 0 Comments | Tags: lua