Lua:如何确定元素是否是表而不是字符串/数字?

unw*_*guy 13 lua lua-table

正如标题所说,我可以做什么功能或检查来确定lua元素是否是一个表?

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

Nat*_*han 31

print(type(elem)) -->table
Run Code Online (Sandbox Code Playgroud)

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


小智 19

在原始问题的背景下,

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

希望这可以帮助.


mle*_*age 7

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

local function istable(t) return type(t) == 'table' end
Run Code Online (Sandbox Code Playgroud)