Lua:如何判断一个元素是表而不是字符串/数字?

27

正如标题所述,我应该使用哪个函数或检查来确定Lua元素是否为表格?

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

40
print(type(elem)) -->table

Lua中的type函数返回其第一个参数的数据类型(字符串)。


1
这对我来说很慢,有其他的方法吗? - Деян Добромиров

33

在原始问题的背景下,

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

希望这可以帮到您。


10

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

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

4

使用type()函数:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接