title: Looking out of bounds in a 2D Lua table
body: <p>I sometimes make small games in Lua, and often have to implement a 2D array as a grid or a board. When I want to check the cells surrounding a particular cell I usually give the 2D array a metatable so that when grid[outOfBoundsNum] is indexed it returns an empty table instead of an error:</p>
  
  <pre><code>setmetatable(grid, {
      __index = 
      function(t, key)
          if not table[key] then
              return {}
          else
              return table[key]
          end
      end})
  </code></pre>
  
  <p>So when <code>grid[outOfBoundsNum][anything]</code> is called, it returns <code>nil</code>. Then, to check surrounding cells I do something like this :</p>
  
  <pre><code>for k, v in ipairs(neighbours) do
      local cell = grid[v[1][v[2]]
      if cell then -- check if this is actually within the 2D array
          if cell == 1 then 
              -- do something
          elseif cell == 2 then
              -- do something else
          ...
      end
  end
  </code></pre>
  
  <p>This works, but it seems awkward to me. Is there a nicer or better way of doing it?</p>