Various fixes to the "Scripting -> GDScript" to respect the GDScript style guide.

This commit is contained in:
Michael Alexsander Silva Dias
2018-04-22 15:15:31 -03:00
parent 5339a43652
commit e173600c79
4 changed files with 256 additions and 234 deletions

View File

@@ -57,19 +57,19 @@ assignment. Example:
Static:
::
.. code:: cpp
int a; // value uninitialized
a = 5; // this is valid
a = "Hi!"; // this is invalid
int a; // Value uninitialized
a = 5; // This is valid
a = "Hi!"; // This is invalid
Dynamic:
::
var a # null by default
a = 5 # valid, 'a' becomes an integer
a = "Hi!" # valid, 'a' changed to a string
a = 5 # Valid, 'a' becomes an integer
a = "Hi!" # Valid, 'a' changed to a string
As function arguments:
~~~~~~~~~~~~~~~~~~~~~~
@@ -79,17 +79,17 @@ different arguments, for example:
Static:
::
.. code:: cpp
void print_value(int value)
{
printf("value is %i\n",value);
void print_value(int value) {
printf("value is %i\n", value);
}
[..]
print_value(55); // valid
print_value("Hello"); // invalid
print_value(55); // Valid
print_value("Hello"); // Invalid
Dynamic:
@@ -97,10 +97,11 @@ Dynamic:
func print_value(value):
print(value)
[..]
print_value(55) # valid
print_value("Hello") # valid
print_value(55) # Valid
print_value("Hello") # Valid
Pointers & referencing:
~~~~~~~~~~~~~~~~~~~~~~~
@@ -127,9 +128,9 @@ too. Some Examples:
void do_something() {
SomeClass *instance = new SomeClass; // created as pointer
use_class(instance); // passed as pointer
delete instance; // otherwise it will leak memory
SomeClass *instance = new SomeClass; // Created as pointer
use_class(instance); // Passed as pointer
delete instance; // Otherwise it will leak memory
}
- Java:
@@ -144,9 +145,9 @@ too. Some Examples:
public final void do_something() {
SomeClass instance = new SomeClass(); // created as reference
use_class(instance); // passed as reference
// garbage collector will get rid of it when not in
SomeClass instance = new SomeClass(); // Created as reference
use_class(instance); // Passed as reference
// Garbage collector will get rid of it when not in
// use and freeze your game randomly for a second
}
@@ -154,13 +155,13 @@ too. Some Examples:
::
func use_class(instance); # does not care about class type
instance.use() # will work with any class that has a ".use()" method.
func use_class(instance); # Does not care about class type
instance.use() # Will work with any class that has a ".use()" method.
func do_something():
var instance = SomeClass.new() # created as reference
use_class(instance) # passed as reference
# will be unreferenced and deleted
var instance = SomeClass.new() # Created as reference
use_class(instance) # Passed as reference
# Will be unreferenced and deleted
In GDScript, only base types (int, float, string and the vector types)
are passed by value to functions (value is copied). Everything else
@@ -176,37 +177,37 @@ Arrays in dynamically typed languages can contain many different mixed
datatypes inside and are always dynamic (can be resized at any time).
Compare for example arrays in statically typed languages:
::
.. code:: cpp
int *array = new int[4]; // create array
array[0] = 10; // initialize manually
array[1] = 20; // can't mix types
int *array = new int[4]; // Create array
array[0] = 10; // Initialize manually
array[1] = 20; // Can't mix types
array[2] = 40;
array[3] = 60;
// can't resize
use_array(array); // passed as pointer
delete[] array; // must be freed
// Can't resize
use_array(array); // Passed as pointer
delete[] array; // Must be freed
//or
// or
std::vector<int> array;
array.resize(4);
array[0] = 10; // initialize manually
array[1] = 20; // can't mix types
array[0] = 10; // Initialize manually
array[1] = 20; // Can't mix types
array[2] = 40;
array[3] = 60;
array.resize(3); // can be resized
use_array(array); // passed reference or value
// freed when stack ends
array.resize(3); // Can be resized
use_array(array); // Passed reference or value
// Freed when stack ends
And in GDScript:
::
var array = [10, "hello", 40, 60] # simple, and can mix types
array.resize(3) # can be resized
use_array(array) # passed as reference
# freed when no longer in use
var array = [10, "hello", 40, 60] # Simple, and can mix types
array.resize(3) # Can be resized
use_array(array) # Passed as reference
# Freed when no longer in use
In dynamically typed languages, arrays can also double as other
datatypes, such as lists:
@@ -245,7 +246,7 @@ Example of Dictionary:
::
var d = {"name": "john", "age": 22} # simple syntax
var d = {"name": "John", "age": 22} # Simple syntax
print("Name: ", d["name"], " Age: ", d["age"])
Dictionaries are also dynamic, keys can be added or removed at any point
@@ -253,16 +254,16 @@ at little cost:
::
d["mother"] = "Rebecca" # addition
d["age"] = 11 # modification
d.erase("name") # removal
d["mother"] = "Rebecca" # Addition
d["age"] = 11 # Modification
d.erase("name") # Removal
In most cases, two-dimensional arrays can often be implemented more
easily with dictionaries. Here's a simple battleship game example:
::
# battleship game
# Battleship game
const SHIP = 0
const SHIP_HIT = 1
@@ -276,13 +277,12 @@ easily with dictionaries. Here's a simple battleship game example:
board[Vector(1, 3)] = SHIP
func missile(pos):
if pos in board: # something at that pos
if board[pos] == SHIP: # there was a ship! hit it
if pos in board: # Something at that pos
if board[pos] == SHIP: # There was a ship! hit it
board[pos] = SHIP_HIT
else:
print("already hit here!") # hey dude you already hit here
else: # nothing, mark as water
print("Already hit here!") # Hey dude you already hit here
else: # Nothing, mark as water
board[pos] = WATER_HIT
func game():
@@ -298,41 +298,41 @@ states and quick structs:
::
# same example, lua-style support
# this syntax is a lot more readable and usable
# Same example, lua-style support.
# This syntax is a lot more readable and usable
var d = {
name = "john",
name = "John",
age = 22
}
print("Name: ", d.name, " Age: ", d.age) # used "." based indexing
print("Name: ", d.name, " Age: ", d.age) # Used "." based indexing
# indexing
# Indexing
d["mother"] = "rebecca"
d.mother = "caroline" # this would work too to create a new key
d["mother"] = "Rebecca"
d.mother = "Caroline" # This would work too to create a new key
For & while
-----------
Iterating in some statically typed languages can be quite complex:
::
.. code:: cpp
const char* strings = new const char*[50];
[..]
for(int i=0; i<50; i++)
for (int i = 0; i < 50; i++)
{
printf("value: %s\n", i, strings[i]);
printf("Value: %s\n", i, strings[i]);
}
// even in STL:
// Even in STL:
for(std::list<std::string>::const_iterator it = strings.begin(); it != strings.end(); it++) {
for (std::list<std::string>::const_iterator it = strings.begin(); it != strings.end(); it++) {
std::cout << *it << std::endl;
}
@@ -363,41 +363,45 @@ The range() function can take 3 arguments:
::
range(n) # will go from 0 to n-1
range(b, n) # will go from b to n-1
range(b, n, s) # will go from b to n-1, in steps of s
range(n) # Will go from 0 to n-1
range(b, n) # Will go from b to n-1
range(b, n, s) # Will go from b to n-1, in steps of s
Some examples:
::
.. code:: cpp
for(int i=0; i<10; i++) {}
for (int i = 0; i < 10; i++) {}
for(int i=5; i<10; i++) {}
for (int i = 5; i < 10; i++) {}
for(int i=5; i<10; i+=2) {}
for (int i = 5; i < 10; i += 2) {}
Translate to:
::
for i in range(10):
pass
for i in range(5, 10):
pass
for i in range(5, 10, 2):
pass
And backwards looping is done through a negative counter:
::
for(int i=10; i>0; i--) {}
for (int i = 10; i > 0; i--) {}
becomes
Becomes:
::
for i in range(10, 0, -1):
pass
While
-----
@@ -421,30 +425,30 @@ functions in your script. An example implementation of a forward iterator follow
::
class FwdIterator:
var start, curr, end, increment
var start, curr, end, increment
func _init(start, stop, inc):
self.start = start
self.curr = start
self.end = stop
self.increment = inc
func _init(start, stop, inc):
self.start = start
self.curr = start
self.end = stop
self.increment = inc
func is_done():
return (curr < end)
func is_done():
return (curr < end)
func do_step():
curr += increment
return is_done()
func do_step():
curr += increment
return is_done()
func _iter_init(arg):
curr = start
return is_done()
func _iter_init(arg):
curr = start
return is_done()
func _iter_next(arg):
return do_step()
func _iter_next(arg):
return do_step()
func _iter_get(arg):
return curr
func _iter_get(arg):
return curr
And it can be used like any other iterator:
@@ -452,7 +456,7 @@ And it can be used like any other iterator:
var itr = FwdIterator.new(0, 6, 2)
for i in itr:
print(i) # Will print 0, 2, and 4
print(i) # Will print 0, 2, and 4
Make sure to reset the state of the iterator in ``_iter_init``, otherwise nested
for-loops that use custom iterators will not work as expected.
@@ -469,10 +473,10 @@ As an example, imagine a situation where a big rock is falling down a
tunnel, smashing everything on its way. The code for the rock, in a
statically typed language would be something like:
::
.. code:: cpp
void BigRollingRock::on_object_hit(Smashable *entity) {
void BigRollingRock::on_object_hit(Smashable *entity)
{
entity->smash();
}

View File

@@ -53,30 +53,30 @@ here's a simple example of how GDScript looks.
::
# a file is a class!
# A file is a class!
# inheritance
# Inheritance
extends BaseClass
# member variables
# Member variables
var a = 5
var s = "Hello"
var arr = [1, 2, 3]
var dict = {"key": "value", 2:3}
# constants
# Constants
const answer = 42
const thename = "Charly"
const ANSWER = 42
const THE_NAME = "Charly"
# enums
# Enums
enum {UNIT_NEUTRAL, UNIT_ENEMY, UNIT_ALLY}
enum Named {THING_1, THING_2, ANOTHER_THING = -1}
# built-in vector types
# Built-in vector types
var v2 = Vector2(1, 2)
var v3 = Vector3(1, 2, 3)
@@ -91,7 +91,7 @@ here's a simple example of how GDScript looks.
elif param2 > 5:
print(param2)
else:
print("fail!")
print("Fail!")
for i in range(20):
print(i)
@@ -99,24 +99,24 @@ here's a simple example of how GDScript looks.
while param2 != 0:
param2 -= 1
var local_var2 = param1+3
var local_var2 = param1 + 3
return local_var2
# functions override functions with the same name on the base/parent class
# if you still want to call them, use '.' (like 'super' in other languages)
# Functions override functions with the same name on the base/parent class.
# If you still want to call them, use '.' (like 'super' in other languages)
func something(p1, p2):
.something(p1, p2)
# inner class
# Inner class
class Something:
var a = 10
# constructor
# Constructor
func _init():
print("constructed!")
print("Constructed!")
var lv = Something.new()
print(lv.a)
@@ -300,7 +300,7 @@ Literals
+--------------------------+--------------------------------+
| ``"Hello"``, ``"Hi"`` | Strings |
+--------------------------+--------------------------------+
| ``"""Hello, Dude"""`` | Multiline string |
| ``"""Hello"""`` | Multiline string |
+--------------------------+--------------------------------+
| ``@"Node/Label"`` | NodePath or StringName |
+--------------------------+--------------------------------+
@@ -315,10 +315,10 @@ considered a comment.
# This is a comment
.. Uncomment me if/when https://github.com/godotengine/godot/issues/1320 gets fixed
Multi-line comments can be created using """ (three quotes in a row) at
the beginning and end of a block of text.
Multi-line comments can be created using """ (three quotes in a row) at
the beginning and end of a block of text. Note that this creates a string,
therefore, it will not be stripped away when the script is compiled.
::
@@ -467,11 +467,11 @@ Starting with Godot 2.1, indices may be negative like in Python, to count from t
var arr = []
arr = [1, 2, 3]
var b = arr[1] # this is 2
var c = arr[arr.size() - 1] # this is 3
var d = arr[-1] # same as the previous line, but shorter
arr[0] = "Hi!" # replacing value 1 with "Hi"
arr.append(4) # array is now ["Hi", 2, 3, 4]
var b = arr[1] # This is 2
var c = arr[arr.size() - 1] # This is 3
var d = arr[-1] # Same as the previous line, but shorter
arr[0] = "Hi!" # Replacing value 1 with "Hi"
arr.append(4) # Array is now ["Hi", 2, 3, 4]
GDScript arrays are allocated linearly in memory for speed. Very
large arrays (more than tens of thousands of elements) may however cause
@@ -495,13 +495,13 @@ Associative container which contains values referenced by unique keys.
::
var d = {4: 5, "a key": "a value", 28: [1, 2, 3]}
var d = {4: 5, "A key": "A value", 28: [1, 2, 3]}
d["Hi!"] = 0
d = {
22: "Value",
"somekey": 2,
"otherkey": [2, 3, 4],
"morekey": "Hello"
22: "value",
"some_key": 2,
"other_key": [2, 3, 4],
"more_key": "Hello"
}
Lua-style table syntax is also supported. Lua-style uses ``=`` instead of ``:``
@@ -512,19 +512,19 @@ start with a digit.
::
var d = {
test22 = "Value",
somekey = 2,
otherkey = [2, 3, 4],
morekey = "Hello"
test22 = "value",
some_key = 2,
other_key = [2, 3, 4],
more_key = "Hello"
}
To add a key to an existing dictionary, access it like an existing key and
assign to it::
var d = {} # create an empty Dictionary
d.waiting = 14 # add String "Waiting" as a key and assign the value 14 to it
d[4] = "hello" # add integer `4` as a key and assign the String "hello" as its value
d["Godot"] = 3.01 # add String "Godot" as a key and assign the value 3.01 to it
var d = {} # Create an empty Dictionary
d.waiting = 14 # Add String "Waiting" as a key and assign the value 14 to it
d[4] = "hello" # Add integer `4` as a key and assign the String "hello" as its value
d["Godot"] = 3.01 # Add String "Godot" as a key and assign the value 3.01 to it
Data
----
@@ -538,10 +538,10 @@ value upon initialization.
::
var a # data type is null by default
var a # Data type is null by default
var b = 5
var c = 3.8
var d = b + c # variables are always initialized in order
var d = b + c # Variables are always initialized in order
Constants
~~~~~~~~~
@@ -551,13 +551,13 @@ expressions and must be assigned on initialization.
::
const a = 5
const b = Vector2(20, 20)
const c = 10 + 20 # constant expression
const d = Vector2(20, 30).x # constant expression: 20
const e = [1, 2, 3, 4][0] # constant expression: 1
const f = sin(20) # sin() can be used in constant expressions
const g = x + 20 # invalid; this is not a constant expression!
const A = 5
const B = Vector2(20, 20)
const C = 10 + 20 # Constant expression
const D = Vector2(20, 30).x # Constant expression: 20
const E = [1, 2, 3, 4][0] # Constant expression: 1
const F = sin(20) # sin() can be used in constant expressions
const G = x + 20 # Invalid; this is not a constant expression!
Enums
^^^^^
@@ -596,10 +596,10 @@ argument, unlike Python).
::
func myfunction(a, b):
func my_function(a, b):
print(a)
print(b)
return a + b # return is optional; without it null is returned
return a + b # Return is optional; without it null is returned
A function can ``return`` at any point. The default return value is ``null``.
@@ -615,12 +615,12 @@ pass it to another function as an argument) one must use the ``call`` or
``funcref`` helpers::
# Call a function by name in one step
mynode.call("myfunction", args)
my_node.call("my_function", args)
# Store a function reference
var myfunc = funcref(mynode, "myfunction")
var my_func = funcref(my_node, "my_function")
# Call stored function reference
myfunc.call_func(args)
my_func.call_func(args)
Remember that default functions like ``_init``, and most
@@ -677,7 +677,7 @@ Short statements can be written on the same line as the condition::
Sometimes you might want to assign a different initial value based on a
boolean expression. In this case ternary-if expressions come in handy::
var x = [true-value] if [expression] else [false-value]
var x = [value] if [expression] else [value]
y += 3 if y < 10 else -1
while
@@ -702,23 +702,23 @@ in the loop variable.
::
for x in [5, 7, 11]:
statement # loop iterates 3 times with x as 5, then 7 and finally 11
statement # Loop iterates 3 times with x as 5, then 7 and finally 11
var dict = {"a": 0, "b": 1, "c": 2}
for i in dict:
print(dict[i])
for i in range(3):
statement # similar to [0, 1, 2] but does not allocate an array
statement # Similar to [0, 1, 2] but does not allocate an array
for i in range(1,3):
statement # similar to [1, 2] but does not allocate an array
statement # Similar to [1, 2] but does not allocate an array
for i in range(2,8,2):
statement # similar to [2, 4, 6] but does not allocate an array
statement # Similar to [2, 4, 6] but does not allocate an array
for c in "Hello":
print(c) # iterate through all characters in a String, print every letter on new line
print(c) # Iterate through all characters in a String, print every letter on new line
match
^^^^^
@@ -786,11 +786,11 @@ There are 6 pattern types:
match x:
1:
print("it's one!")
print("It's one!")
2:
print("it's one times two!")
print("It's one times two!")
_:
print("it's not 1 or 2. I don't care tbh.")
print("It's not 1 or 2. I don't care tbh.")
- binding pattern
@@ -799,11 +799,11 @@ There are 6 pattern types:
match x:
1:
print("it's one!")
print("It's one!")
2:
print("it's one times two!")
print("It's one times two!")
var new_var:
print("it's not 1 or 2, it's ", new_var)
print("It's not 1 or 2, it's ", new_var)
- array pattern
@@ -817,13 +817,13 @@ There are 6 pattern types:
match x:
[]:
print("empty array")
print("Empty array")
[1, 3, "test", null]:
print("very specific array")
print("Very specific array")
[var start, _, "test"]:
print("first element is ", start, ", and the last is \"test\"")
print("First element is ", start, ", and the last is \"test\"")
[42, ..]:
print("open ended array")
print("Open ended array")
- dictionary pattern
Works in the same way as the array pattern. Every key has to be a constant pattern.
@@ -840,13 +840,13 @@ There are 6 pattern types:
match x:
{}:
print("empty dict")
{"name": "dennis"}:
print("the name is dennis")
{"name": "dennis", "age": var age}:
print("dennis is ", age, " years old.")
print("Empty dict")
{"name": "Dennis"}:
print("The name is Dennis")
{"name": "Dennis", "age": var age}:
print("Dennis is ", age, " years old.")
{"name", "age"}:
print("has a name and an age, but it's not dennis :(")
print("Has a name and an age, but it's not Dennis :(")
{"key": "godotisawesome", ..}:
print("I only checked for one entry and ignored the rest")
@@ -855,9 +855,9 @@ Multipatterns:
match x:
1, 2, 3:
print("it's 1 - 3")
"sword", "splashpotion", "fist":
print("yep, you've taken damage")
print("It's 1 - 3")
"Sword", "Splash potion", "Fist":
print("Yep, you've taken damage")
@@ -877,7 +877,7 @@ Below is an example of a class file.
::
# saved as a file named myclass.gd
# Saved as a file named myclass.gd
var a = 5
@@ -915,12 +915,12 @@ the ``is`` keyword can be used:
::
# Cache the enemy class
const enemy_class = preload("enemy.gd")
const Enemy = preload("enemy.gd")
# [...]
# use 'is' to check inheritance
if (entity is enemy_class):
# Use 'is' to check inheritance
if (entity is Enemy):
entity.apply_damage()
To call a function in a *base class* (i.e. one ``extend``-ed in your current class),
@@ -937,7 +937,7 @@ to call them, you can use ``.`` like the ``super`` keyword in other languages:
::
func some_func(x):
.some_func(x) # calls same function on the parent class
.some_func(x) # Calls same function on the parent class
Class Constructor
^^^^^^^^^^^^^^^^^
@@ -984,14 +984,14 @@ either the ``load`` or ``preload`` functions (see below). Instancing of a loaded
class resource is done by calling the ``new`` function on the class object::
# Load the class resource when calling load()
var MyClass = load("myclass.gd")
var my_class = load("myclass.gd")
# Preload the class only once at compile time
var MyClass2 = preload("myclass.gd")
const MyClass = preload("myclass.gd")
func _init():
var a = MyClass.new()
a.somefunction()
a.some_function()
Exports
~~~~~~~
@@ -1003,7 +1003,7 @@ is done by using the ``export`` keyword::
extends Button
export var number = 5 # value will be saved and visible in the property editor
export var number = 5 # Value will be saved and visible in the property editor
An exported variable must be initialized to a constant expression or have an
export hint in the form of an argument to the export keyword (see below).
@@ -1170,22 +1170,22 @@ with the new value. Vice-versa, when ``variable`` is accessed, the *getter* func
::
var myvar setget myvar_set,myvar_get
var myvar setget my_var_set, my_var_get
func myvar_set(newvalue):
myvar=newvalue
func my_var_set(new_value):
my_var = new_value
func myvar_get():
return myvar # getter must return a value
func my_var_get():
return my_var # Getter must return a value
Either of the *setter* or *getter* functions can be omitted:
::
# Only a setter
var myvar = 5 setget myvar_set
var my_var = 5 setget myvar_set
# Only a getter (note the comma)
var myvar = 5 setget ,myvar_get
var my_var = 5 setget ,myvar_get
Get/Setters are especially useful when exporting variables to editor in tool
scripts or plugins, for validating input.
@@ -1197,12 +1197,12 @@ illustration of this:
func _init():
# Does not trigger setter/getter
myinteger = 5
print(myinteger)
my_integer = 5
print(my_integer)
# Does trigger setter/getter
self.myinteger = 5
print(self.myinteger)
self.my_integer = 5
print(self.my_integer)
Tool mode
~~~~~~~~~
@@ -1245,7 +1245,7 @@ Declaring a signal in GDScript is easy using the `signal` keyword.
# No arguments
signal your_signal_name
# With arguments
signal your_signal_name_with_args(a,b)
signal your_signal_name_with_args(a, b)
These signals, just like regular signals, can be connected in the editor
or from code. Just take the instance of a class where the signal was
@@ -1291,7 +1291,7 @@ Object.emit_signal method:
func _at_some_func():
emit_signal("your_signal_name")
emit_signal("your_signal_name_with_args", 55, 128)
someinstance.emit_signal("somesignal")
some_instance.emit_signal("some_signal")
Coroutines with yield
~~~~~~~~~~~~~~~~~~~~~
@@ -1306,13 +1306,13 @@ an example:
::
func myfunc():
print("hello")
func my_func():
print("Hello")
yield()
print("world")
func _ready():
var y = myfunc()
var y = my_func()
# Function state saved in 'y'
print("my dear")
y.resume()
@@ -1322,7 +1322,7 @@ Will print:
::
hello
Hello
my dear
world
@@ -1331,13 +1331,13 @@ example:
::
func myfunc():
print("hello")
func my_func():
print("Hello")
print(yield())
return "cheers!"
func _ready():
var y = myfunc()
var y = my_func()
# Function state saved in 'y'
print(y.resume("world"))
# 'y' resumed and is now an invalid state
@@ -1346,7 +1346,7 @@ Will print:
::
hello
Hello
world
cheers!
@@ -1378,10 +1378,10 @@ be obtained when a call to Node._ready() is made.
::
var mylabel
var my_label
func _ready():
mylabel = get_node("MyLabel")
my_label = get_node("MyLabel")
This can get a little cumbersome, especially when nodes and external
references pile up. For this, GDScript has the ``onready`` keyword, that
@@ -1390,7 +1390,7 @@ can replace the above code with a single line:
::
onready var mylabel = get_node("MyLabel")
onready var my_label = get_node("MyLabel")
Assert keyword
~~~~~~~~~~~~~~

View File

@@ -19,7 +19,9 @@ strings could be cumbersome.
Usage in GDScript
-----------------
Examine this concrete GDScript example::
Examine this concrete GDScript example:
::
# Define a format string with placeholder '%s'
var format_string = "We're waiting for %s."
@@ -28,7 +30,7 @@ Examine this concrete GDScript example::
var actual_string = format_string % "Godot"
print(actual_string)
# output: "We're waiting for Godot."
# Output: "We're waiting for Godot."
Placeholders always start with a ``%``, but the next character or characters,
the *format specifier*, determines how the given value is converted to a
@@ -48,16 +50,18 @@ value. The method can handle arrays or dictionaries for the key/value pairs.
Arrays can be used as key, index, or mixed style (see below examples). Order only
matters when the index or mixed style of Array is used.
A quick example in GDScript::
A quick example in GDScript:
::
# 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"})
var actual_string = format_string.format({"str": "Godot"})
print(actual_string)
# output: "We're waiting for Godot"
# Output: "We're waiting for Godot"
There are other `format specifiers`_, but they are only applicable when using
the ``%`` operator.
@@ -68,13 +72,15 @@ Multiple placeholders
Format strings may contain multiple placeholders. In such a case, the values
are handed in the form of an array, one value per placeholder (unless using a
format specifier with ``*``, see `dynamic padding`_)::
format specifier with ``*``, see `dynamic padding`_):
::
var format_string = "%s was reluctant to learn %s, but now he enjoys it."
var actual_string = format_string % ["Estragon", "GDScript"]
print(actual_string)
# output: "Estragon was reluctant to learn GDScript, but now he enjoys it."
# Output: "Estragon was reluctant to learn GDScript, but now he enjoys it."
Note the values are inserted in order. Remember all placeholders must be
replaced at once, so there must be an appropriate number of values.
@@ -149,14 +155,18 @@ The ``.`` (*dot*), ``*`` (*asterisk*), ``-`` (*minus sign*) and digit
values aligned vertically as if in a column, provided a fixed-width font is
used.
To pad a string to a minimum length, add an integer to the specifier::
To pad a string to a minimum length, add an integer to the specifier:
::
print("%10d" % 12345)
# output: " 12345"
# 5 leading spaces for a total length of 10
If the integer starts with ``0``, integral values are padded with zeroes
instead of white space::
instead of white space:
::
print("%010d" % 12345)
# output: "0000012345"
@@ -168,16 +178,18 @@ the dot.
::
# pad to minimum length of 10, round to 3 decimal places
# Pad to minimum length of 10, round to 3 decimal places
print("%10.3f" % 10000.5555)
# output: " 10000.556"
# Output: " 10000.556"
# 1 leading space
The ``-`` character will cause padding to the right rather than the left,
useful for right text alignment::
useful for right text alignment:
::
print("%-10d" % 12345678)
# output: "12345678 "
# Output: "12345678 "
# 2 trailing spaces
@@ -187,16 +199,20 @@ Dynamic padding
By using the ``*`` (*asterisk*) character, the padding or precision can be set
without modifying the format string. It is used in place of an integer in the
format specifier. The values for padding and precision are then passed when
formatting::
formatting:
::
var format_string = "%*.*f"
# pad to length of 7, round to 3 decimal places:
# Pad to length of 7, round to 3 decimal places:
print(format_string % [7, 3, 8.8888])
# output: " 8.889"
# Output: " 8.889"
# 2 leading spaces
It is still possible to pad with zeroes in integer placeholders by adding ``0``
before ``*``::
before ``*``:
::
print("%0*d" % [2, 3])
#output: "03"
@@ -206,11 +222,13 @@ Escape sequence
---------------
To insert a literal ``%`` character into a format string, it must be escaped to
avoid reading it as a placeholder. This is done by doubling the character::
avoid reading it as a placeholder. This is done by doubling the character:
::
var health = 56
print("Remaining health: %d%%" % health)
# output: "Remaining health: 56%"
# Output: "Remaining health: 56%"
Format method examples

View File

@@ -30,14 +30,14 @@ Indent size: 4 *(editor default)*
Each indent level should be one greater than the block containing it.
**Good**
**Good**:
::
for i in range(10):
print("hello")
**Bad**
**Bad**:
::
@@ -50,7 +50,7 @@ Each indent level should be one greater than the block containing it.
Use 2 indent levels to distinguish continuation lines from
regular code blocks.
**Good**
**Good**:
::
@@ -58,7 +58,7 @@ regular code blocks.
sprite.get_scale(), Vector2(2.0, 2.0), 0.3,
Tween.TRANS_QUAD, Tween.EASE_OUT)
**Bad**
**Bad**:
::
@@ -80,7 +80,7 @@ Never combine multiple statements on a single line. No, C programmers,
not with a single line conditional statement (except with the ternary
operator)!
**Good**
**Good**:
::
@@ -90,7 +90,7 @@ operator)!
if flag:
print("flagged")
**Bad**
**Bad**:
::
@@ -104,14 +104,14 @@ Avoid Unnecessary Parentheses
Avoid parentheses in expressions and conditional statements. Unless
necessary for order of operations, they only reduce readability.
**Good**
**Good**:
::
if is_colliding():
queue_free()
**Bad**
**Bad**:
::
@@ -124,7 +124,7 @@ Whitespace
Always use one space around operators and after commas. Avoid extra
spaces in dictionary references and function calls, or to create "columns."
**Good**
**Good**:
::
@@ -134,7 +134,7 @@ spaces in dictionary references and function calls, or to create "columns."
myarray = [4, 5, 6]
print('foo')
**Bad**
**Bad**:
::
@@ -144,7 +144,7 @@ spaces in dictionary references and function calls, or to create "columns."
myarray = [4,5,6]
print ('foo')
**Never!**
**NEVER**:
::