我怎么知道一个表是否是一个数组? [英] How do I know if a table is an array?

查看:64
本文介绍了我怎么知道一个表是否是一个数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个简单的优化的 JSON 函数. Lua使用表来表示数组,但是在JSON中我需要识别它们之间.使用以下代码:

I'm developing a simple optimized JSON function. Lua uses tables to represent arrays but in JSON I need to recognize between them. The code below is used:

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不同.

As you can see in JSON reference an object is what is called a table in Lua and it's different from an array.

问题是如何检测表是否被用作数组?

The question is how I can detect if a table is being used as an array?

  • 当然,一种解决方案是遍历所有对,看看它们是否只有数字连续键,但这不够快.
  • 另一种解决方案是在表中放置一个标志,说它是一个数组而不是对象.

有没有更简单/更智能的解决方案?

Any simpler/smarter solution?

推荐答案

谢谢.我开发了以下代码,它可以正常工作:

Thanks. I developed the following code and it works:

---Checks if a table is used as an array. That is: the keys start with one and are sequential numbers
-- @param t table
-- @return nil,error string if t is not a table
-- @return true/false if t is an array/isn't an array
-- NOTE: it returns true for an empty table
function isArray(t)
    if type(t)~="table" then return nil,"Argument is not a table! It is: "..type(t) end
    --check if all the table keys are numerical and count their number
    local count=0
    for k,v in pairs(t) do
        if type(k)~="number" then return false else count=count+1 end
    end
    --all keys are numerical. now let's see if they are sequential and start with 1
    for i=1,count do
        --Hint: the VALUE might be "nil", in that case "not t[i]" isn't enough, that's why we check the type
        if not t[i] and type(t[i])~="nil" then return false end
    end
    return true
end

这篇关于我怎么知道一个表是否是一个数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆