Search code examples
lua

Lua unusual variable name (question mark variable)


I have stumbled upon this line of code and I am not sure what the [ ? ] part represents (my guess is it's a sort of a wildcard but I searched it for a while and couldn't find anything):

['?'] = function() return is_canadian and "eh" or "" end

I understand that RHS is a functional ternary operator. I am curious about the LHS and what it actually is.

Edit: reference (2nd example):

http://lua-users.org/wiki/SwitchStatement


Solution

  • Actually, it is quite simple.

      local t = {
        a = "aah",
        b = "bee",
        c = "see",
    

    It maps each letter to a sound pronunciation. Here, a need to be pronounced aah and b need to be pronounced bee and so on. Some letters have a different pronunciation if in american english or canadian english. So not every letter can be mapped to a single sound.

    z = function() return is_canadian and "zed" or "zee" end,
    ['?'] = function() return is_canadian and "eh" or "" end
    

    In the mapping, the letter z and the letter ? have a different prononciation in american english or canadian english. When the program will try to get the prononciation of '?', it will calls a function to check whether the user want to use canadian english or another english and the function will returns either zed or zee.

    Finally, the 2 following notations have the same meaning:

      local t1 = {
        a     = "aah",
        b     = "bee",
        ["?"] = "bee"
      }
    
      local t2 = {
        ["a"] = "aah",
        ["b"] = "bee",
        ["?"] = "bee"
      }