在 Lua 中 concat 函数是 concatenate(连锁, 连接)的缩写,table.concat() 函数列出参数中指定 table 的数组部分从 start 位置到 end 位置的所有元素, 元素间以指定的分隔符(sep)隔开。
table.concat(table [, sep [, start [, end]]])
参数 | 描述 |
---|---|
table | 要连接的表。 |
sep | 分隔符 |
start | 开始索引。 |
end | 结束索引 |
返回连接后的字符串。
使用 concat() 函数,实现表连接
#!/usr/bin/lua
print("haicoder(www.haicoder.net)\n")
fruits = {"banana", "orange", "apple"}
print(string.format("str1 = %s", table.concat(fruits)))
print(string.format("str2 = %s", table.concat(fruits, ", ")))
print(string.format("str3 = %s", table.concat(fruits,", ", 2,3)))
程序运行后,控制台输出如下:
我们使用了 table.concat 实现了表的拼接,第一次拼接时,我们没有指定任何的参数,因此,结果就是将表中的所有数据直接拼接在一起。第二次,我们指定了拼接的分隔符。
最后一次拼接的时候,我们指定了分隔符,并且指定从第二个元素开始拼接,到第三个元素结束。
在 Lua 中 concat 函数是 concatenate(连锁, 连接)的缩写,table.concat() 函数列出参数中指定 table 的数组部分从 start 位置到 end 位置的所有元素, 元素间以指定的分隔符(sep)隔开。