我正在开发一个简单优化的JSON函数。 Lua使用表来表示数组,但是在JSON中,我需要在它们之间进行识别。下面的代码用于:如何知道表是否是数组?
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))
正如你可以看到JSON引用object
是所谓在Lua一个table
,它是从array
不同。
问题是我如何检测表是否被用作数组?
- 当然,一个解决方案是通过所有对,看看他们是否只有数字连续键,但这不够快。
- 另一种解决方案是在表中放置一个标志,表示它是一个数组而不是对象。
任何更简单/更智能的解决方案?
参见:http://stackoverflow.com/questions/6077006/how-can-i-check-if-a-lua-table-contains-only-sequential-numeric-indices/6080274#6080274 – BMitch