Lua 文字列を結合するサンプル

目次

..演算子で結合する

local str1 = "ab"
local str2 = "cd"
local result = str1 .. str2
print(result)  -- abcd

3行目は、..演算子で文字列を結合しています。

 

table.concat()で結合する

local words = {"ab", "cd", "ef"}
local result = table.concat(words, "-")
print(result)  -- ab-cd-ef

local words = {"ab", "cd", "ef"}
local result = table.concat(words)
print(result)  -- abcdef

concatの2つめの引数で文字列を結合します。
2つめの引数は省略可能です。

 

string.format()で結合する

string.format() は、文字列のフォーマットを指定して整形する関数です。

local color1 = "red"
local color2 = "blue"
local result1 = string.format("This color is %s and %s", color1, color2)
print(result1)  -- This color is red and blue

local num1 = 11
local num2 = 3.14159
local result2 = string.format("This number is %d and %.2f", num1, num2)
print(result2)  -- This number is 11 and 3.14

print(string.format("%04d", 7))   -- 0007

3行目の%Sは文字列が入ります。
8行目の%dは数値で、%.2fは小数点です。
11行目は、前ゼロがついています。

関連の記事

△上に戻る