テーブルのキーにテーブルを入れる

Luaでは、テーブルは同一判定であって、同値判定ではない。すなわち、

{1,2,3} == {1,2,3}    --> false

となる。なので、テーブルをテーブルのキーにすることは出来ない。


では、どうすれば良いのかと言うと、テーブルを文字列化してキーとすれば良い。

function table.tostring(self)
  local strs = {}
  local idxs = {}
  for i,v in ipairs(self) do
    if tonumber(v) then
      table.insert(strs, v)
    else
      table.insert(strs, '"'..v..'"')
    end
    idxs[i] = true
  end
  for k,v in pairs(self) do
    if not idxs[k] then
      if type(k) == 'number' then
        table.insert(strs, '['..k..']='..tostring(v))
      else
        table.insert(strs, tostring(k)..'='..tostring(v))
      end
    end
  end
  return '{' .. table.concat(strs, ', ') .. '}'
end

t = {1,2,3}
t2 = {}
t2[table.tostring(t)] = 99
print(t2[table.tostring({1,2,3})])    --> 99