title: How do I know if a table is an array?
body: <p>I'm developing a simple optimized <a href="http://json.org/">JSON</a> function. Lua uses tables to represent arrays but in JSON I need to recognize between them. The code below is used:</p>
  
  <pre><code>t={
      a="hi",
      b=100
  }
  
  function table2json(t,formatted)
  if type(t)~="table" then return nil,"Parameter is not a table. It is: "..type(t)    end
  
  local ret=""--return value
  local lvl=0 --indentation level
  local INDENT="  " --OPTION: the characters put in front of every line for indentation
  function addToRet(str) if formatted then ret=ret..string.rep(INDENT,lvl)..str.."\n" else ret=ret..str end end
  
  addToRet("{")
  lvl=1
  for k,v in pairs(t) do
      local typeof=type(v)
      if typeof=="string" then
          addToRet(k..":\""..v.."\"")
      elseif typeof=="number" then
          addToRet(k..":"..v)
      end
  end
  lvl=0
  addToRet("}")
  
  return ret
  end
  
  print(table2json(t,true))
  </code></pre>
  
  <p>As you can see in JSON reference an <code>object</code> is what is called a <code>table</code> in Lua and it's different from an <code>array</code>.</p>
  
  <p>The question is how I can detect if a table is being used as an array?</p>
  
  <ul>
  <li>One solution of course is to go through all pairs and see if they only have numerical consecutive keys but that's not fast enough.</li>
  <li>Another solution is to put a flag in the table that says it is an array not an object.</li>
  </ul>
  
  <p>Any simpler/smarter solution?</p>