Sto sviluppando una semplice funzione ottimizzata JSON. Lua usa le tabelle per rappresentare gli array ma in JSON ho bisogno di riconoscere tra loro. Il codice di seguito viene utilizzato:Come faccio a sapere se una tabella è una matrice?
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))
Come si può vedere in JSON riferimento un object
è quello che viene chiamato un table
in Lua ed è diverso da un array
.
La domanda è come posso rilevare se una tabella viene utilizzato come un array?
- Una soluzione, naturalmente, è quello di passare attraverso tutte le coppie e vedere se hanno solo i tasti numerici consecutivi ma non è abbastanza veloce.
- Un'altra soluzione è di mettere un flag nella tabella che dice che è un non matrice un oggetto.
Qualsiasi soluzione più semplice/intelligente?
See: http://stackoverflow.com/questions/6077006/how-can-i-check-if-a-lua-table-contains-only-sequential-numeric-indices/6080274#6080274 – BMitch