zoukankan      html  css  js  c++  java
  • 关于 lua table表

    --table 是lua的一种数据结构用来帮助我们创建不同的数据类型。如:数组和字典
    --lua table 使用关联型数组,你可以用任意类型的值来做数组的索引,但这个值不能是nil
    --lua table 是不固定大小的,你可以根据自己需要进行扩容

    一、lua 的table 表存的数据类型

      这个 table 表 强大,可以存放好多种数据类型

    
    
    tab1 = {1, 2 ,3} -- 类似数组
    tab2 = {"a", "b", "c"}  -- 类似数组
    tab3 =  {["a"]="aa", ["b"]="bb"}   -- 键值对
    1. 存函数 tb = {} tb.func = function () print("hanshu") end print(tb.func()) 2. 判断一个table的元素是否是另一个table的元素(关于函数) tab={}
    tab.a
    =function () print(1) return 1 end
    tab.b=function () print(2) return 1 end
    tab.c=function () print(3) return 1 end local zhi={"a","c"} for key,value in pairs(zhi) do print(key,value) for key ,func in pairs(tab) do if value == func then func() print("ok") end end end
    输出结果:
    1
    a 2 c


    3. 判断有没有函数 tab={}
    function a() print(1) return 1 end
    function b() print(2) return 1 end
    function c() print(3) return 1 end local tab={["a"]=a, ["b"]=b, ["c"]=c} local zhi={"a","c"} for key,value in pairs(zhi) do print(key,value) if tab[value]() then print("ok") end end
    输出结果:
    1
    a 1 ok 2 c 3 ok

    2、lua 的table的 遍历

      pairs遍历表中全部key,value.
      ipairs从下标为1开始遍历,然后下标累加1,如果某个下标元素不存在就终止遍历。这就导致如果下标不连续或者不是从1开始的表就会中断或者遍历不到元素。

    local tt ={[1] = "test3",[4] = "test4",[5] = "test5"}
    
    for i,v in pairs(tt) do        -- 输出 "test4" "test3" "test5"
        print( tt[i] )
    end
    
    for i,v in ipairs(tt) do    -- 输出 "test3" k=2时断开
        print( tt[i] )
    end
    
    ----------------------------------------------------
    tbl = {"alpha", "beta", [3] = "uno", ["two"] = "dos"}
    
    for i,v in ipairs(tbl) do    --输出前三个
        print( tbl[i] )
    end
    
    for i,v in pairs(tbl) do    --全部输出
        print( tbl[i] )
    end
  • 相关阅读:
    Shiro权限验证
    5种设计模式整理
    多模块的SpringBoot项目
    Go使用数据库
    使用Go mod
    docker基本使用
    Go的IO操作
    实现一个网盘存储……
    Go的网络编程
    学习golang的历程
  • 原文地址:https://www.cnblogs.com/chenpython123/p/10699517.html
Copyright © 2011-2022 走看看