【问题标题】:Lua: How to find out if an element is a table instead of a string/number?Lua:如何找出一个元素是否是一个表格而不是一个字符串/数字?
【发布时间】:2012-07-20 07:27:57
【问题描述】:

正如标题所说,我可以通过什么函数或检查来确定 lua 元素是否为表格?

local elem = {['1'] = test, ['2'] = testtwo}
if (elem is table?) // <== should return true

【问题讨论】:

    标签: lua lua-table


    【解决方案1】:
    print(type(elem)) -->table
    

    Lua 中的 type 函数返回它的第一个参数是什么数据类型(字符串)

    【讨论】:

    • 这对我来说很慢还有其他方法吗?
    【解决方案2】:

    在原始问题的上下文中,

    local elem = {['1'] = test, ['2'] = testtwo}
    if (type(elem) == "table") then
      -- do stuff
    else
      -- do other stuff instead
    end
    

    希望这会有所帮助。

    【讨论】:

      【解决方案3】:

      您可能会发现这有助于提高可读性:

      local function istable(t) return type(t) == 'table' end
      

      【讨论】:

        【解决方案4】:

        使用type():

        local elem = {1,2,3}
        print(type(elem) == "table")
        -- true
        

        【讨论】:

          猜你喜欢
          • 2010-10-13
          • 2022-03-31
          • 1970-01-01
          • 2021-02-14
          • 2012-11-23
          • 2013-05-12
          • 2011-06-12
          相关资源
          最近更新 更多