String Formatting in GDScript
Our first program will demonstrate string formatting in GDScript. Here’s the full source code and explanation:
extends Node
class Point:
var x: int
var y: int
func _init(_x: int, _y: int):
x = _x
y = _y
func _ready():
# GDScript offers several ways to format strings
# For example, this prints an instance of our Point class
var p = Point.new(1, 2)
print("struct1: ", p)
# To include the struct's field names, we can use the str() function
print("struct2: ", str(p))
# To print the type of a value, use typeof()
print("type: ", typeof(p))
# Formatting booleans is straightforward
print("bool: ", true)
# For integers, we can use the standard print function
print("int: ", 123)
# To print a binary representation, we can use String.bin()
print("bin: ", String.num(14, 2))
# To print the character corresponding to an integer
print("char: ", char(33))
# For hexadecimal representation
print("hex: ", "%X" % 456)
# For basic decimal formatting of floats
print("float1: %.6f" % 78.9)
# Scientific notation
print("float2: %.6e" % 123400000.0)
# For basic string printing
print('str1: "string"')
# To include quotes in the output
print("str2: ", '"string"')
# To print a representation of a pointer (object ID in GDScript)
print("pointer: ", p.get_instance_id())
# Controlling width and precision
print("width1: |%6d|%6d|" % [12, 345])
print("width2: |%6.2f|%6.2f|" % [1.2, 3.45])
# Left-justify with the - flag
print("width3: |%-6.2f|%-6.2f|" % [1.2, 3.45])
# Controlling width for strings
print("width4: |%6s|%6s|" % ["foo", "b"])
print("width5: |%-6s|%-6s|" % ["foo", "b"])
# Formatting and returning a string without printing
var s = "sprintf: a %s" % "string"
print(s)
# Printing to stderr (in GDScript, this is done with push_error)
push_error("io: an error")
To run the program, save this code in a script attached to a Node in your Godot project and run the scene.
GDScript provides various string formatting options, although they differ slightly from Go’s. The %
operator is used for string formatting, similar to Python. For more complex formatting, GDScript offers functions like str()
and String.num()
.
Note that GDScript doesn’t have a direct equivalent to Go’s fmt.Sprintf()
or fmt.Fprintf()
. Instead, you can use string formatting with the %
operator to create formatted strings, and print()
or push_error()
to output to the console or error log respectively.
Remember that GDScript is designed for use within the Godot game engine, so some concepts (like writing to arbitrary file descriptors) may not have direct equivalents. However, for most string formatting needs, GDScript provides powerful and flexible options.