@GDScript
Built-in GDScript functions.
Description
List of core built-in GDScript functions. Math functions and other utilities. Everything else is provided by objects. (Keywords: builtin, built in, global functions.)
Methods
Constants
- PI = 3.141593 —- Constant that represents how many times the diameter of a circle fits around its perimeter. This is equivalent to
TAU / 2. - TAU = 6.283185 —- The circle constant, the circumference of the unit circle in radians. This is equivalent to
PI * 2, or 360 degrees in rotations. - INF = inf —- Positive floating-point infinity. This is the result of floating-point division when the divisor is
0.0. For negative infinity, use-INF. Dividing by-0.0will result in negative infinity if the numerator is positive, so dividing by0.0is not the same as dividing by-0.0(despite0.0 == -0.0returningtrue). Note: Numeric infinity is only a concept with floating-point numbers, and has no equivalent for integers. Dividing an integer number by0will not result in INF and will result in a run-time error instead. - NAN = nan —- “Not a Number”, an invalid floating-point value. NAN has special properties, including that it is not equal to itself (
NAN == NANreturnsfalse). It is output by some invalid operations, such as dividing floating-point0.0by0.0. Note: “Not a Number” is only a concept with floating-point numbers, and has no equivalent for integers. Dividing an integer0by0will not result in NAN and will result in a run-time error instead.Method Descriptions
- Color Color8 ( int r8, int g8, int b8, int a8=255 )
Returns a color constructed from integer red, green, blue, and alpha channels. Each channel should have 8 bits of information ranging from 0 to 255.
r8red channelg8green channelb8blue channela8alpha channelred = Color8(255, 0, 0)
- Color ColorN ( String name, float alpha=1.0 )
namewithalpharanging from 0 to 1.
Color.red = ColorN("red", 1)
- float abs ( float s )
s(i.e. positive value).a = abs(-1) # a is 1
- float acos ( float s )
sin radians. Use to get the angle of cosines.smust be between-1.0and1.0(inclusive), otherwise, acos will return NAN.# c is 0.523599 or 30 degrees if converted with rad2deg(s)c = acos(0.866025)
- float asin ( float s )
sin radians. Use to get the angle of sines.smust be between-1.0and1.0(inclusive), otherwise, asin will return NAN.# s is 0.523599 or 30 degrees if converted with rad2deg(s)s = asin(0.5)
- assert ( bool condition, String message=”” )
conditionistrue. If theconditionisfalse, an error is generated. When running from the editor, the running project will also be paused until you resume it. This can be used as a stronger form of push_error for reporting errors to project developers or add-on users. Note: For performance reasons, the code inside assert is only executed in debug builds or when running the project from the editor. Don’t include code that has side effects in an assert call. Otherwise, the project will behave differently when exported in release mode.messageargument, if given, is shown in addition to the generic “Assertion failed” message. You can use this to provide additional details about why the assertion failed.# Imagine we always want speed to be between 0 and 20.var speed = -10assert(speed < 20) # True, the program will continueassert(speed >= 0) # False, the program will stopassert(speed >= 0 and speed < 20) # You can also combine the two conditional statements in one checkassert(speed < 20, "speed = %f, but the speed limit is 20" % speed) # Show a message with clarifying details
- float atan ( float s )
sin radians. Use it to get the angle from an angle’s tangent in trigonometry:atan(tan(angle)) == angle. atan2 if you have bothyandx.a = atan(0.5) # a is 0.463648
- float atan2 ( float y, float x )
y/xin radians. Use to get the angle of tangenty/x. To compute the value, the method takes into account the sign of both arguments in order to determine the quadrant. Important note: The Y coordinate comes first, by convention.a = atan2(0, -1) # a is 3.141593
- Variant bytes2var ( PoolByteArray bytes, bool allow_objects=false )
allow_objectsistruedecoding objects is allowed. WARNING: Deserialized object can contain code which gets executed. Do not use this option if the serialized object comes from untrusted sources to avoid potential security threats (remote code execution).
- Vector2 cartesian2polar ( float x, float y ) Converts a 2D point expressed in the cartesian coordinate system (X and Y axis) to the polar coordinate system (a distance from the origin and an angle).
- float ceil ( float s )
supward (towards positive infinity), returning the smallest whole number that is not less thans.
floor, round, stepify, and int.a = ceil(1.45) # a is 2.0a = ceil(1.001) # a is 2.0
- String char ( int code )
Returns a character as a String of the given Unicode code point (which is compatible with ASCII code).
ord.a = char(65) # a is "A"a = char(65 + 32) # a is "a"a = char(8364) # a is "€"
- float clamp ( float value, float min, float max )
valueand returns a value not less thanminand not more thanmax.a = clamp(1000, 1, 20) # a is 20a = clamp(-10, 1, 20) # a is 1a = clamp(15, 1, 20) # a is 15
- Variant convert ( Variant what, int type )
typeparameter uses the Variant.Type values.a = Vector2(1, 0)# Prints 1print(a.length())a = convert(a, TYPE_STRING)# Prints 6 as "(1, 0)" is 6 charactersprint(a.length())
- float cos ( float s )
sin radians.a = cos(TAU) # a is 1.0a = cos(PI) # a is -1.0
- float cosh ( float s )
sin radians.print(cosh(1)) # Prints 1.543081
- float db2linear ( float db ) Converts from decibels to linear energy (audio).
- int decimals ( float step ) step_decimals.
- float dectime ( float value, float amount, float step )
Note:
dectimehas been deprecated and will be removed in Godot 4.0, please use move_toward instead.valuedecreased bystep*amount.a = dectime(60, 10, 0.1)) # a is 59.0
- bool deep_equal ( Variant a, Variant b )
Array or Dictionary up to its deepest level.
==in a number of ways: null,int,float,String,ObjectandRIDbothdeep_equaland==work the same.Dictionary,==considers equality if, and only if, both variables point to the very sameDictionary, with no recursion or awareness of the contents at all.Array,==considers equality if, and only if, each item in the firstArrayis equal to its counterpart in the secondArray, as told by==itself. That implies that==recurses intoArray, but not intoDictionary.Dictionaryis potentially involved, if you want a true content-aware comparison, you have to usedeep_equal.
- float deg2rad ( float deg )
Converts an angle expressed in degrees to radians.
r = deg2rad(180) # r is 3.141593
- Object dict2inst ( Dictionary dict ) inst2dict) back to an instance. Useful for deserializing.
- float ease ( float s, float curve )
xbased on an easing function defined withcurve. This easing function is based on an exponent. Thecurvecan be any floating-point number, with specific values leading to the following behaviors: ``` - Lower than -1.0 (exclusive): Ease in-out- 1.0: Linear- Between -1.0 and 0.0 (exclusive): Ease out-in- 0.0: Constant- Between 0.0 to 1.0 (exclusive): Ease out- 1.0: Linear- Greater than 1.0 (exclusive): Ease in ``` ease() curve values cheatsheet smoothstep. If you need to perform more advanced transitions, use Tween or AnimationPlayer.
- float exp ( float s )
e to the power of
sand returns it. e has an approximate value of 2.71828, and can be obtained withexp(1). pow.a = exp(2) # Approximately 7.39
- float floor ( float s )
sdownward (towards negative infinity), returning the largest whole number that is not more thans.
ceil, round, stepify, and int. Note: This method returns a float. If you need an integer anda = floor(2.45) # a is 2.0a = floor(2.99) # a is 2.0a = floor(-2.99) # a is -3.0
sis a non-negative number, you can useint(s)directly.
- float fmod ( float a, float b )
a/b, keeping the sign ofa.
For the integer remainder operation, use the % operator.r = fmod(7, 5.5) # r is 1.5
- float fposmod ( float a, float b )
a/bthat wraps equally in positive and negative.
Produces:for i in 7: var x = 0.5 * i - 1.5 print("%4.1f %4.1f %4.1f" % [x, fmod(x, 1.5), fposmod(x, 1.5)])
-1.5 -0.0 0.0-1.0 -1.0 0.5-0.5 -0.5 1.0 0.0 0.0 0.0 0.5 0.5 0.5 1.0 1.0 1.0 1.5 0.0 0.0
- FuncRef funcref ( Object instance, String funcname )
funcnamein theinstancenode. As functions aren’t first-class objects in GDscript, usefuncrefto store a FuncRef in a variable and call it later.func foo(): return("bar")a = funcref(self, "foo")print(a.call_func()) # Prints bar
- Array get_stack ( )
Returns an array of dictionaries representing the current call stack.
would printfunc _ready(): foo()func foo(): bar()func bar(): print(get_stack())
[{function:bar, line:12, source:res://script.gd}, {function:foo, line:9, source:res://script.gd}, {function:_ready, line:6, source:res://script.gd}]
- int hash ( Variant var )
Returns the integer hash of the variable passed.
print(hash("a")) # Prints 177670
- Dictionary inst2dict ( Object inst )
Returns the passed instance converted to a dictionary (useful for serializing).
Prints out:var foo = "bar"func _ready(): var d = inst2dict(self) print(d.keys()) print(d.values())
[@subpath, @path, foo][, res://test.gd, bar]
- Object instance_from_id ( int instance_id )
instance_id. All Objects have a unique instance ID.var foo = "bar"func _ready(): var id = get_instance_id() var inst = instance_from_id(id) print(inst.foo) # Prints bar
- float inverse_lerp ( float from, float to, float weight )
fromandto, and the interpolated value specified inweight. The returned value will be between0.0and1.0ifweightis betweenfromandto(inclusive). Ifweightis located outside this range, then an extrapolation factor will be returned (return value lower than0.0or greater than1.0).
lerp which performs the reverse of this operation.# The interpolation ratio in the `lerp()` call below is 0.75.var middle = lerp(20, 30, 0.75)# `middle` is now 27.5.# Now, we pretend to have forgotten the original ratio and want to get it back.var ratio = inverse_lerp(20, 30, 27.5)# `ratio` is now 0.75.
- bool is_equal_approx ( float a, float b )
trueifaandbare approximately equal to each other.aandbare within a small internal epsilon of each other, which scales with the magnitude of the numbers. Infinity values of the same sign are considered equal.
- bool is_inf ( float s )
sis an infinity value (either positive infinity or negative infinity).
- bool is_instance_valid ( Object instance )
instanceis a valid object (e.g. has not been deleted from memory).
- bool is_nan ( float s )
sis a NaN (“Not a Number” or invalid) value.
- bool is_zero_approx ( float s )
trueifsis zero or almost zero. is_equal_approx with one value as zero.
- int len ( Variant var )
var. Length is the character count of String, element count of Array, size of Dictionary, etc. Note: Generates a fatal error if Variant can not provide a length.a = [1, 2, 3, 4]len(a) # Returns 4
- Variant lerp ( Variant from, Variant to, float weight )
weight. To perform interpolation,weightshould be between0.0and1.0(inclusive). However, values outside this range are allowed and can be used to perform extrapolation.fromandtoarguments are of type int or float, the return value is a float. Vector2, Vector3 or Color), the return value will be of the same type (lerpthen calls the vector type’slinear_interpolatemethod).
inverse_lerp which performs the reverse of this operation. To perform eased interpolation with lerp, combine it with ease or smoothstep.lerp(0, 4, 0.75) # Returns 3.0lerp(Vector2(1, 5), Vector2(3, 2), 0.5) # Returns Vector2(2, 3.5)
- float lerp_angle ( float from, float to, float weight )
Linearly interpolates between two angles (in radians) by a normalized value.
lerp, but interpolates correctly when the angles wrap around TAU. To perform eased interpolation with lerp_angle, combine it with ease or smoothstep.
Note: This method lerps through the shortest path betweenextends Spritevar elapsed = 0.0func _process(delta): var min_angle = deg2rad(0.0) var max_angle = deg2rad(90.0) rotation = lerp_angle(min_angle, max_angle, elapsed) elapsed += delta
fromandto. However, when these two angles are approximatelyPI + k * TAUapart for any integerk, it’s not obvious which way they lerp due to floating-point precision errors. For example,lerp_angle(0, PI, weight)lerps counter-clockwise, whilelerp_angle(0, PI + 5 * TAU, weight)lerps clockwise.
- float linear2db ( float nrg )
Converts from linear energy to decibels (audio). This can be used to implement volume sliders that behave as expected (since volume isn’t linear). Example:
# "Slider" refers to a node that inherits Range such as HSlider or VSlider.# Its range must be configured to go from 0 to 1.# Change the bus name if you'd like to change the volume of a specific bus only.AudioServer.set_bus_volume_db(AudioServer.get_bus_index("Master"), linear2db($Slider.value))
- Resource load ( String path )
path. The resource is loaded on the method call (unless it’s referenced already elsewhere, e.g. in another script or in the scene), which might cause slight delay, especially when loading scenes. To avoid unnecessary delays when loading something multiple times, either store the resource in a variable or use preload. Note: Resource paths can be obtained by right-clicking on a resource in the FileSystem dock and choosing “Copy Path” or by dragging the file from the FileSystem dock into the script.
Important: The path must be absolute, a local path will just return# Load a scene called main located in the root of the project directory and cache it in a variable.var main = load("res://main.tscn") # main will contain a PackedScene resource.
null. ResourceLoader.load, which can be used for more advanced scenarios.
- float log ( float s )
Natural logarithm. The amount of time needed to reach a certain level of continuous growth.
Note: This is not the same as the “log” function on most calculators, which uses a base 10 logarithm.
Note: The logarithm oflog(10) # Returns 2.302585
0returns-inf, while negative values return-nan.
- float max ( float a, float b )
Returns the maximum of two values.
max(1, 2) # Returns 2max(-3.99, -4) # Returns -3.99
- float min ( float a, float b )
Returns the minimum of two values.
min(1, 2) # Returns 1min(-3.99, -4) # Returns -4
- float move_toward ( float from, float to, float delta )
fromtowardtoby thedeltavalue.deltavalue to move away.move_toward(5, 10, 4) # Returns 9move_toward(10, 5, 4) # Returns 6move_toward(10, 5, -1.5) # Returns 11.5
- int nearest_po2 ( int value )
value.awherea = pow(2, n)such thatvalue <= afor some non-negative integern.
WARNING: Due to the way it is implemented, this function returnsnearest_po2(3) # Returns 4nearest_po2(4) # Returns 4nearest_po2(5) # Returns 8nearest_po2(0) # Returns 0 (this may not be what you expect)nearest_po2(-1) # Returns 0 (this may not be what you expect)
0rather than1for non-positive values ofvalue(in reality, 1 is the smallest integer power of 2).
- int ord ( String char )
char.
char.a = ord("A") # a is 65a = ord("a") # a is 97a = ord("€") # a is 8364
- Variant parse_json ( String json )
typeof to check if the Variant’s type is what you expect.)
Note: The JSON specification does not define integer or float types, but only a number type. Therefore, parsing a JSON text will convert all numerical values to float types.
Note: JSON objects do not preserve key order like Godot dictionaries, thus, you should not rely on keys being in a certain order if a dictionary is constructed from JSON. In contrast, JSON arrays retain the order of their elements:
JSON for an alternative way to parse JSON text.var p = JSON.parse('["hello", "world", "!"]')if typeof(p.result) == TYPE_ARRAY: print(p.result[0]) # Prints "hello"else: push_error("Unexpected results.")
- Vector2 polar2cartesian ( float r, float th )
rand an angleth) to the cartesian coordinate system (X and Y axis).
- int posmod ( int a, int b )
a/bthat wraps equally in positive and negative.
Produces:for i in range(-3, 4): print("%2d %2d %2d" % [i, i % 3, posmod(i, 3)])
-3 0 0-2 -2 1-1 -1 2 0 0 0 1 1 1 2 2 2 3 0 0
- float pow ( float base, float exp )
baseraised to the power ofexp.pow(2, 5) # Returns 32.0
- Resource preload ( String path )
Resource from the filesystem located at
path. The resource is loaded during script parsing, i.e. is loaded with the script and preload effectively acts as a reference to that resource. Note that the method requires a constant path. If you want to load a resource from a dynamic/variable path, use load. Note: Resource paths can be obtained by right clicking on a resource in the Assets Panel and choosing “Copy Path” or by dragging the file from the FileSystem dock into the script.# Instance a scene.var diamond = preload("res://diamond.tscn").instance()
- print ( … ) vararg
Converts one or more arguments of any type to string in the best way possible and prints them to the console.
Note: Consider using push_error and push_warning to print error and warning messages instead of print. This distinguishes them from print messages used for debugging purposes, while also displaying a stack trace when an error or warning is printed.a = [1, 2, 3]print("a", "=", a) # Prints a=[1, 2, 3]
- print_debug ( … ) vararg
print, but includes the current stack frame when running with the debugger turned on.
Output in the console would look something like this:
Test print At: res://test.gd:15:_process()
- print_stack ( )
Prints a stack track at code location, only works when running with debugger turned on.
Output in the console would look something like this:
Frame 0 - res://test.gd:16 in function '_process'
- printerr ( … ) vararg
Prints one or more arguments to strings in the best way possible to standard error line.
printerr("prints to stderr")
- printraw ( … ) vararg
Prints one or more arguments to strings in the best way possible to console. No newline is added at the end.
Note: Due to limitations with Godot’s built-in console, this only prints to the terminal. If you need to print in the editor, use another method, such as print.printraw("A")printraw("B")# Prints AB
- prints ( … ) vararg
Prints one or more arguments to the console with a space between each argument.
prints("A", "B", "C") # Prints A B C
- printt ( … ) vararg
Prints one or more arguments to the console with a tab between each argument.
printt("A", "B", "C") # Prints A B C
- push_error ( String message )
Pushes an error message to Godot’s built-in debugger and to the OS terminal.
Note: Errors printed this way will not pause project execution. To print an error message and pause project execution in debug builds, usepush_error("test error") # Prints "test error" to debugger and terminal as error call
assert(false, "test error")instead.
- push_warning ( String message )
Pushes a warning message to Godot’s built-in debugger and to the OS terminal.
push_warning("test warning") # Prints "test warning" to debugger and terminal as warning call
- float rad2deg ( float rad )
Converts an angle expressed in radians to degrees.
rad2deg(0.523599) # Returns 30.0
- float rand_range ( float from, float to )
fromandto(both endpoints inclusive).
Note: This is equivalent toprints(rand_range(0, 1), rand_range(0, 1)) # Prints e.g. 0.135591 0.405263
randf() * (to - from) + from.
- Array rand_seed ( int seed )
seed, and an array with both number and new seed is returned. “Seed” here refers to the internal state of the pseudo random number generator. The internal state of the current implementation is 64 bits.
- float randf ( )
[0, 1].randf() # Returns e.g. 0.375671
- int randi ( )
[0, N - 1](where N is smaller than 2^32).randi() # Returns random integer between 0 and 2^32 - 1randi() % 20 # Returns random integer between 0 and 19randi() % 100 # Returns random integer between 0 and 99randi() % 100 + 1 # Returns random integer between 1 and 100
- randomize ( )
Randomizes the seed (or the internal state) of the random number generator. Current implementation reseeds using a number based on time.
func _ready(): randomize()
- Array range ( … ) vararg
range can be called in three ways:
range(n: int): Starts from 0, increases by steps of 1, and stops beforen. The argumentnis exclusive.range(b: int, n: int): Starts fromb, increases by steps of 1, and stops beforen. The argumentsbandnare inclusive and exclusive, respectively.range(b: int, n: int, s: int): Starts fromb, increases/decreases by steps ofs, and stops beforen. The argumentsbandnare inclusive and exclusive, respectively. The argumentscan be negative, but not0. Ifsis0, an error message is printed. range converts all arguments to int before processing. Note: Returns an empty array if no value meets the value constraint (e.g.range(2, 5, -1)orrange(5, 5, 1)). Examples:
Array backwards, use:print(range(4)) # Prints [0, 1, 2, 3]print(range(2, 5)) # Prints [2, 3, 4]print(range(0, 6, 2)) # Prints [0, 2, 4]print(range(4, 1, -1)) # Prints [4, 3, 2]
Output: ```var array = [3, 6, 9]for i in range(array.size(), 0, -1): print(array[i - 1])
---- float **range_lerp** **(** float value, float istart, float istop, float ostart, float ostop **)**`value` from range `[istart, istop]` to `[ostart, ostop]`.
range_lerp(75, 0, 100, -1, 1) # Returns 0.5
---- float **round** **(** float s **)**`s` to the nearest whole number, with halfway cases rounded away from zero.
a = round(2.49) # a is 2.0a = round(2.5) # a is 3.0a = round(2.51) # a is 3.0
floor, ceil, stepify, and int.---- **seed** **(** int seed **)**Sets seed for the random number generator.
my_seed = “Godot Rocks”seed(my_seed.hash())
---- float **sign** **(** float s **)**`s`: -1 or 1. Returns 0 if `s` is 0.
sign(-6) # Returns -1sign(0) # Returns 0sign(6) # Returns 1
---- float **sin** **(** float s **)**`s` in radians.
sin(0.523599) # Returns 0.5
---- float **sinh** **(** float s **)**`s`.
a = log(2.0) # Returns 0.693147sinh(a) # Returns 0.75
---- float **smoothstep** **(** float from, float to, float s **)**`s` between `0` and `1`, based on the where `s` lies with respect to the edges `from` and `to`.`0` if `s <= from`, and `1` if `s >= to`. If `s` lies between `from` and `to`, the returned value follows an S-shaped curve that maps `s` between `0` and `1`.`f(y) = 3*y^2 - 2*y^3` where `y = (x-from) / (to-from)`.
smoothstep(0, 2, -5.0) # Returns 0.0smoothstep(0, 2, 0.5) # Returns 0.15625smoothstep(0, 2, 1.0) # Returns 0.5smoothstep(0, 2, 2.0) # Returns 1.0
ease with a curve value of `-1.6521`, smoothstep returns the smoothest possible curve with no sudden changes in the derivative. If you need to perform more advanced transitions, use Tween or AnimationPlayer.Comparison between smoothstep() and ease(x, -1.6521) return values---- float **sqrt** **(** float s **)**`s`, where `s` is a non-negative number.
sqrt(9) # Returns 3
**Note:** Negative values of `s` return NaN. If you need negative inputs, use `System.Numerics.Complex` in C#.---- int **step_decimals** **(** float step **)**Returns the position of the first non-zero digit, after the decimal point. Note that the maximum return value is 10, which is a design decision in the implementation.
n = step_decimals(5) # n is 0n = step_decimals(1.0005) # n is 4n = step_decimals(0.000000005) # n is 9
---- float **stepify** **(** float s, float step **)**`s` to a given `step`. This can also be used to round a floating point number to an arbitrary number of decimals.
stepify(100, 32) # Returns 96.0stepify(3.14159, 0.01) # Returns 3.14
ceil, floor, round, and int.---- String **str** **(** … **)** varargConverts one or more arguments of any type to string in the best way possible.
var a = [10, 20, 30]var b = str(a);len(a) # Returns 3len(b) # Returns 12
---- Variant **str2var** **(** String string **)**var2str to the original value.
a = ‘{ “a”: 1, “b”: 2 }’b = str2var(a)print(b[“a”]) # Prints 1
---- float **tan** **(** float s **)**`s` in radians.
tan(deg2rad(45)) # Returns 1
---- float **tanh** **(** float s **)**`s`.
a = log(2.0) # a is 0.693147b = tanh(a) # b is 0.6
---- String **to_json** **(** Variant var **)**Variant `var` to JSON text and return the result. Useful for serializing data to store or send over the network.
Both numbers below are integers.a = { “a”: 1, “b”: 2 }b = to_json(a)print(b) # {“a”:1, “b”:2}# Both numbers above are floats, even if they display without any decimal places.
**Note:** The JSON specification does not define integer or float types, but only a *number* type. Therefore, converting a Variant to JSON text will convert all numerical values to float types.JSON for an alternative way to convert a Variant to JSON text.---- bool **type_exists** **(** String type **)**ClassDB.
type_exists(“Sprite”) # Returns truetype_exists(“Variant”) # Returns false
---- int **typeof** **(** Variant what **)**Variant.Type values.
p = parse_json(‘[“a”, “b”, “c”]’)if typeof(p) == TYPE_ARRAY: print(p[0]) # Prints aelse: print(“unexpected results”)
---- String **validate_json** **(** String json **)**`json` is valid JSON data. Returns an empty string if valid, or an error message otherwise.
j = to_json([1, 2, 3])v = validate_json(j)if not v: print(“Valid JSON.”)else: push_error(“Invalid JSON: “ + v)
---- PoolByteArray **var2bytes** **(** Variant var, bool full_objects=false **)**`full_objects` is `true` encoding objects is allowed (and can potentially include code).---- String **var2str** **(** Variant var **)**`var` to a formatted string that can later be parsed using str2var.
a = { “a”: 1, “b”: 2 }print(var2str(a))
prints
{“a”: 1,”b”: 2}
---- WeakRef **weakref** **(** Object obj **)**Returns a weak reference to an object.A weak reference to an object is not enough to keep the object alive: when the only remaining references to a referent are weak references, garbage collection is free to destroy the referent and reuse its memory for something else. However, until the object is actually destroyed the weak reference may return the object even if there are no strong references to it.---- float **wrapf** **(** float value, float min, float max **)**`value` between `min` and `max`.Usable for creating loop-alike behavior or infinite surfaces.
Infinite loop between 5.0 and 9.9value = wrapf(value + 0.1, 5.0, 10.0)
```# Infinite rotation (in radians)angle = wrapf(angle + 0.1, 0.0, TAU)
# Infinite rotation (in radians)angle = wrapf(angle + 0.1, -PI, PI)
Note: If min is 0, this is equivalent to fposmod, so prefer using that instead.
wrapf is more flexible than using the fposmod approach by giving the user control over the minimum value.
- int wrapi ( int value, int min, int max )
valuebetweenminandmax. Usable for creating loop-alike behavior or infinite surfaces.# Infinite loop between 5 and 9frame = wrapi(frame + 1, 5, 10)
Note: If# result is -2var result = wrapi(-6, -5, -1)
minis0, this is equivalent to posmod, so prefer using that instead.wrapiis more flexible than using the posmod approach by giving the user control over the minimum value.
- GDScriptFunctionState yield ( Object object=null, String signal=”” )
Stops the function execution and returns the current suspended state to the calling function.
GDScriptFunctionState.resume on the state to resume execution. This invalidates the state. Within the resumed function,
yield()returns whatever was passed to theresume()function call.yield()returns the argument passed toemit_signal()if the signal takes only one argument, or an array containing all the arguments passed toemit_signal()if the signal takes multiple arguments.yieldto wait for a function to finish:func _ready(): yield(countdown(), "completed") # waiting for the countdown() function to complete print('Ready')func countdown(): yield(get_tree(), "idle_frame") # returns a GDScriptFunctionState object to _ready() print(3) yield(get_tree().create_timer(1.0), "timeout") print(2) yield(get_tree().create_timer(1.0), "timeout") print(1) yield(get_tree().create_timer(1.0), "timeout")# prints:# 3# 2# 1# Ready
completedsignal will be emitted automatically when the function returns. It can, therefore, be used as thesignalparameter of theyieldmethod to resume.GDScriptFunctionState. Noticeyield(get_tree(), "idle_frame")from the above example.
