我正在開發一個簡單優化的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