如何检查一个值是否为表格。

如同名字所示......你不能这样说:

3[7] --> 尝试获取数字值的索引
"fpp"[7] --> 尝试获取字符串值的索引

我知道type()函数,但我尽量避免使用它因为它很慢。

if(type({}) == "table") ...
if(string.sub(tostring({}),1,5) == "table")...

function ArrayCount(arArr)
  if(not arArr) then return 0 end
  if(not (type(arArr) == "table")) then return 0 end
  if(not (arArr and arArr[1])) then return return 0 end
  local Count = 1
  while(arArr[Count]) do Count = Count + 1 end
  return (Count - 1)
end

ArrayCount(3)
ArrayCount("I am a string!")
点赞
用户1190388
用户1190388

type函数并不慢。更新你的函数,简单地改为:

function ArrayCount(arArr)
  if type( arArr ) ~= "table" then return 0 end
  return #arArr - 1
end
2015-09-12 15:13:53