• Lua 判断表是否为空方法


    【1】判断表为空的方法

    目前为止,Lua语言中判断table表是否为空有三种方式:

    (1)#table,当table为数组时直接返回table表的长度。

    (2)当table是字典时,返回table的长度

    1 function table.size(t)
    2     local s = 0;
    3     for k, v in pairs(t) do
    4         if v ~= nil then s = s + 1 end
    5     end
    6     return s;
    7 end

    (3)next(table),利用next函数进行判断。

     1 local t = {hello = 1, world = 2, lucy = 3}
     2 local k, v
     3 while true do
     4     k, v = next(t, k)
     5     print(k ,v)
     6     if not v then break end
     7 end
     8 
     9 --[[ 执行结果
    10 hello    1
    11 lucy    3
    12 world    2
    13 nil    nil
    14 ]]
    15 
    16 local tt = {}
    17 
    18 function isEmpty(tbl)
    19     if next(tbl) ~= nil then
    20         print("is not empty.")
    21     else
    22         print("is empty.")
    23     end
    24 end
    25 
    26 print(isEmpty(t))
    27 print(isEmpty(tt))
    28 
    29 --[[ 执行结果
    30 is not empty.
    31 is empty.
    32 ]]

    Good Good Study, Day Day Up.

    顺序 选择 循环 总结

  • 相关阅读:
    国产html编辑器
    豆瓣90mhz电台还行
    购物搜索
    linode vps 优化集锦
    这个系统,我看行,
    代理网站
    合理设置域名TTL值给网站加速
    dns切换到dnspod
    elixir usage
    JSSH介绍
  • 原文地址:https://www.cnblogs.com/Braveliu/p/9792642.html
Copyright © 2020-2023  润新知