View Single Post
01-26-14, 09:32 PM   #10
Phanx
Cat.
 
Phanx's Avatar
AddOn Author - Click to view addons
Join Date: Mar 2006
Posts: 5,617
Originally Posted by Xrystal View Post
... I thought was the same as ["health"]["UNIT_HEALTH"] if, and only if, there is no variable set with those names but it does make sense that it wouldn't assume they were text values.
Yeah, if you have not definited UNIT_HEALTH as a variable then looking up myTable[UNIT_HEALTH] will just give you an error about attempting to index a nil value. The only place you don't need quotes around a string value is when defining a key inside a table contructor, in which context strings are the only type of keys you don't need to enclose in square brackets.

Code:
local myTable = {
     -- Now you're inside a table constructor!
     -- You don't need to quote strings used as keys here.
     -- These will all work:
     myKey = "myValue", -- "myKey" is a string, but it doesn't need quotes and brackets here
     ["otherKey"] = "otherValue", -- "otherKey" is also a string
     [12] = "twelve", -- 12 is not a string
     [function(x) return x-1 end] = "okay!", -- yes, you can use functions as keys!
     [UnitHealth] = 47, -- UnitHealth is a (reference to a) function
     [RAID_CLASS_COLORS] = function() print("cat") end, -- and tables too!
     ["RAID_CLASS_COLORS"] = "x", -- but this key is a string, not a table

     -- But these will not work without brackets, because the keys aren't strings:
     14 = "wrong",
     function(x) return x-1 end = "also wrong",
     { sub = "table" } = "and wrong again!",
}
Even if you already have a variable with the same name, you still don't need quotes for string-type keys inside a table constructor; this is perfectly valid:

Code:
local class = UnitClass("player")
local playerInfo = {
     class = class, -- the key (left side) is the string "class", and the value (right side) is the value of the variable class
}
However, your strategy of always quoting strings is a good one for avoiding confusion.
__________________
Retired author of too many addons.
Message me if you're interested in taking over one of my addons.
Don’t message me about addon bugs or programming questions.

Last edited by Phanx : 01-26-14 at 09:35 PM.
  Reply With Quote