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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通