string.format
code:Lua
str = textmodule.string.format(format, arg1, arg2, ...)
モジュール
引数
table:_
変数 型 概要
1 format string 元の文字列
2 arg1 number / string / boolean / userdata / nil 1番目の引数
3 arg2 number / string / boolean / userdata / nil 2番目の引数
...
N argN number / string / boolean / userdata / nil N番目の引数
返り値
table:_
変数 型 概要
1 str string 整形された文字列
概要
引数argNの値を、formatの指示に従い整形する。
formatの構文はこちらを参照。整形に失敗した場合は、エラーを発出する。 数値、文字列、ブーリアン、nilのほかに、時間クラスも整形が可能。 対応していない型の引数は、ポインタとして扱われる。
なお、引数に与えられた数値は全て浮動小数点実数として扱われる。
故に、整数を表す"{0:d}"のような構文は使用することが出来ない。
時間クラスは、内部的にはutc_clockからsystem_clockに変換されてから整形されるため注意が必要。
例
code:Lua
require("textmodule")
-- 1つの引数を整形
t = textmodule.string.format("The answer is {}", 24)
print(t) -- The answer is 24.0
-- 2つの引数を整形
textmodule.string.format("The answer is {} {}", "approximately", 50)
print(t) -- The answer is approximately 50.0
-- 引数の番号を指定して整形
t = textmodule.string.format("{0} {2} {1} {0}", "first", "second", "third")
print(t) -- first third second first
-- 数値の精度を指定
t = textmodule.string.format("{0:.0f} < {0:.2f} < {0:.8f}", math.pi)
print(t) -- 3 < 3.14 < 3.14159265
-- 時刻クラスを整形
t = textmodule.string.format("{:%Y-%m-%d %H:%M:%S}", textmodule.time.now())
print(t) -- 2022-12-09 15:08:48