GodotEngine GDScriptフォーマット文字列
GDScriptフォーマット文字列 — Godot Engine (stable)の日本語のドキュメント
Godot EngineのGDScriptでフォーマット文字列使う場合のドキュメント
文字列の中で %s などのプレースホルダーを仕込んでおき、% オペレーターで置換する値を指定する
例えば cost と damage 変数が別で宣言されていて、textにそれらの値を入れ込みたい場合は
code:format_string.py
export var cost = 2
export var damage = 5
var format_string = "Cost: %s, Damage: %s"
func _process(delta):
$Label.text = format_string % cost, damage
$Label.text = format_string % [cost, damage] がフォーマット文字列使用箇所
この方法を使わずに、他のプログラミング言語でよくある以下の書き方をするとエラーになる
"Cost: " + cost + ", Damage: " + damage
エラー内容は、「int を stringに変換できないよ」
GDScriptは文字列連結時にintを暗黙変換してくれない
以下だったらエラーなしでいける
$Label.text = "Cost: " + str(cost) + ", Damage: " + str(damage)
フォーマット文字列を使うと、自動的に str() 変換してくれている
ブール値は "True" または "False" に変わります。整数または実数は10進数になります。
%sなどによるプレースホルダー形式では出現順序を気にする必要がある
出現順序が不定で、keyValue形式で指定したい場合は String.format()関数を使う
GDScriptでテキストをフォーマットする別の方法、すなわち String.format() メソッドもあります。文字列内に出現するすべてのキーを対応する値に置き換えます。 このメソッドは、キー/値ペアの配列または辞書を処理できます。
code:string.format_sample.py
# Define a format string
var format_string = "We're waiting for {str}"
# Using the 'format' method, replace the 'str' placeholder
var actual_string = format_string.format({"str": "Godot"})
print(actual_string)
# Output: "We're waiting for Godot"