Lua--学习--7 Table 构建

2.5.7 – Table Constructors

Table constructors are expressions that create tables. Every time a constructor is evaluated, a new table is created. A constructor can be used to create an empty table or to create a table and initialize some of its fields. The general syntax for constructors is

	tableconstructor ::= `{´ [fieldlist] `}´
	fieldlist ::= field {fieldsep field} [fieldsep]
	field ::= `[´ exp `]´ `=´ exp | Name `=´ exp | exp
	fieldsep ::= `,´ | `;´

Each field of the form [exp1] = exp2 adds to the new table an entry with key exp1 and value exp2. A field of the form name = exp is equivalent to ["name"] = exp. Finally, fields of the form exp are equivalent to [i] = exp, where i are consecutive numerical integers, starting with 1. Fields in the other formats do not affect this counting. For example,

     a = { [f(1)] = g; "x", "y"; x = 1, f(x), [30] = 23; 45 }

is equivalent to

     do
       local t = {}
       t[f(1)] = g
       t[1] = "x"         -- 1st exp
       t[2] = "y"         -- 2nd exp
       t.x = 1            -- t["x"] = 1
       t[3] = f(x)        -- 3rd exp
       t[30] = 23
       t[4] = 45          -- 4th exp
       a = t
     end

If the last field in the list has the form exp and the expression is a function call or a vararg expression, then all values returned by this expression enter the list consecutively (see §2.5.8). To avoid this, enclose the function call or the vararg expression in parentheses (see §2.5).

The field list can have an optional trailing separator, as a convenience for machine-generated code.

 

 

复制代码
语法:
表名称={字段List}
字段List=字段1,字段2;字段3,...
字段:构成形式  ,
        1、Name=value  如:city='tianJin'
        2、exp=exp  如:'na'..'me'="lihui".."zhang"
        3、value  如:40 (数值) 男 (字符串)
     4、Name=exp
     5、exp=Value
     6、exp --遵循之前的返回值数量调整原则
例子
复制代码

 

 

a1='na'
a2='me'
t={[a1..a2]='li'..'Hui';city="tianjin",40,} --最后的一个逗号或分号可有可无
print(t["name"]) --指定KEY 为索引
print(t.city)  ---

             --注意:没有指定key为下表,默认以索引为下表,
print(t[1])  --因为是第一个出现的下标所以是1

结果 :

 

liHui
tianjin
40

 

复制代码
a1='na'
a2='me'
function mv(a,b) 
        return a,b;
end
t={[a1..a2]='li'..'Hui';city="tianjin",40,mv('first','sencond'),sex='nan'}
 
for i,v in pairs(t) do
    print(v)
end


结果:
40
first
liHui
nan
tianjin
复制代码

 

复制代码
a1='na'
a2='me'
function mv(a,b) 
        return a,b;
end
t={[a1..a2]='li'..'Hui';city="tianjin",40,sex='nan',mv('first','sencond')}
 
for i,v in pairs(t) do
    print(v)
end
复制代码

结果

40
first
sencond
liHui
tianjin
nan

 

posted on   hztech  阅读(20)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示