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 2023-03-05 13:31  hztech  阅读(14)  评论(0编辑  收藏  举报

导航