Attention: Here be dragons

This is the latest (unstable) version of this documentation, which may document features not available in or compatible with released stable versions of Godot.

Array

內建的資料結構,可儲存一連串元素。

說明

An array data structure that can contain a sequence of elements of any Variant type by default. Values can optionally be constrained to a specific type by creating a typed array. Elements are accessed by a numerical index starting at 0. Negative indices are used to count from the back (-1 is the last element, -2 is the second to last, etc.).

var array = ["First", 2, 3, "Last"]
print(array[0])  # Prints "First"
print(array[2])  # Prints 3
print(array[-1]) # Prints "Last"

array[1] = "Second"
print(array[1])  # Prints "Second"
print(array[-3]) # Prints "Second"

# This typed array can only contain integers.
# Attempting to add any other type will result in an error.
var typed_array: Array[int] = [1, 2, 3]

Note: Arrays are always passed by reference. To get a copy of an array that can be modified independently of the original array, use duplicate().

Note: Erasing elements while iterating over arrays is not supported and will result in unpredictable behavior.

Note: In a boolean context, an array will evaluate to false if it's empty ([]). Otherwise, an array will always evaluate to true.

Differences between packed arrays, typed arrays, and untyped arrays: Packed arrays are generally faster to iterate on and modify compared to a typed array of the same type (e.g. PackedInt64Array versus Array[int]). Also, packed arrays consume less memory. As a downside, packed arrays are less flexible as they don't offer as many convenience methods such as map(). Typed arrays are in turn faster to iterate on and modify than untyped arrays.

備註

使用 C# 操作此 API 時有顯著差異,詳見 C# API 與 GDScript 的不同

建構子

Array

Array()

Array

Array(base: Array, type: int, class_name: StringName, script: Variant)

Array

Array(from: Array)

Array

Array(from: PackedByteArray)

Array

Array(from: PackedColorArray)

Array

Array(from: PackedFloat32Array)

Array

Array(from: PackedFloat64Array)

Array

Array(from: PackedInt32Array)

Array

Array(from: PackedInt64Array)

Array

Array(from: PackedStringArray)

Array

Array(from: PackedVector2Array)

Array

Array(from: PackedVector3Array)

Array

Array(from: PackedVector4Array)

方法

bool

all(method: Callable) const

bool

any(method: Callable) const

void

append(value: Variant)

void

append_array(array: Array)

void

assign(array: Array)

Variant

back() const

int

bsearch(value: Variant, before: bool = true) const

int

bsearch_custom(value: Variant, func: Callable, before: bool = true) const

void

clear()

int

count(value: Variant) const

Array

duplicate(deep: bool = false) const

Array

duplicate_deep(deep_subresources_mode: int = 1) const

void

erase(value: Variant)

void

fill(value: Variant)

Array

filter(method: Callable) const

int

find(what: Variant, from: int = 0) const

int

find_custom(method: Callable, from: int = 0) const

Variant

front() const

Variant

get(index: int) const

int

get_typed_builtin() const

StringName

get_typed_class_name() const

Variant

get_typed_script() const

bool

has(value: Variant) const

int

hash() const

int

insert(position: int, value: Variant)

bool

is_empty() const

bool

is_read_only() const

bool

is_same_typed(array: Array) const

bool

is_typed() const

void

make_read_only()

Array

map(method: Callable) const

Variant

max() const

Variant

min() const

Variant

pick_random() const

Variant

pop_at(position: int)

Variant

pop_back()

Variant

pop_front()

void

push_back(value: Variant)

void

push_front(value: Variant)

Variant

reduce(method: Callable, accum: Variant = null) const

void

remove_at(position: int)

int

resize(size: int)

void

reverse()

int

rfind(what: Variant, from: int = -1) const

int

rfind_custom(method: Callable, from: int = -1) const

void

set(index: int, value: Variant)

void

shuffle()

int

size() const

Array

slice(begin: int, end: int = 2147483647, step: int = 1, deep: bool = false) const

void

sort()

void

sort_custom(func: Callable)

運算子

bool

operator !=(right: Array)

Array

operator +(right: Array)

bool

operator <(right: Array)

bool

operator <=(right: Array)

bool

operator ==(right: Array)

bool

operator >(right: Array)

bool

operator >=(right: Array)

Variant

operator [](index: int)


建構子說明

Array Array() 🔗

建構空的 Array


Array Array(base: Array, type: int, class_name: StringName, script: Variant)

base 陣列建立一個「型別化陣列」。型別化陣列只能包含指定型別的元素,或繼承自指定類別的元素,具體由建構子的參數決定:

type 不是 @GlobalScope.TYPE_OBJECT,則 class_name 必須為空的 StringName,且 script 必須為 null

class_name Sword
extends Node

class Stats:
    pass

func _ready():
    var a = Array([], TYPE_INT, "", null)               # Array[int]
    var b = Array([], TYPE_OBJECT, "Node", null)        # Array[Node]
    var c = Array([], TYPE_OBJECT, "Node", Sword)       # Array[Sword]
    var d = Array([], TYPE_OBJECT, "RefCounted", Stats) # Array[Stats]

必要時會轉換 base 陣列中的元素;若無法轉換,或 base 已是型別化陣列,則建構子會失敗並回傳空的 Array

在 GDScript 中通常不需要呼叫此建構子,因為可透過靜態型別直接建立型別化陣列:

var numbers: Array[float] = []
var children: Array[Node] = [$Node, $Sprite2D, $RigidBody3D]

var integers: Array[int] = [0.2, 4.5, -2.0]
print(integers) # 輸出 [0, 4, -2]

Array Array(from: Array)

回傳與 from 相同的陣列。若需副本,請使用 duplicate()


Array Array(from: PackedByteArray)

PackedByteArray 建構陣列。


Array Array(from: PackedColorArray)

PackedColorArray 建構陣列。


Array Array(from: PackedFloat32Array)

PackedFloat32Array 建構陣列。


Array Array(from: PackedFloat64Array)

PackedFloat64Array 建構陣列。


Array Array(from: PackedInt32Array)

PackedInt32Array 建構陣列。


Array Array(from: PackedInt64Array)

PackedInt64Array 建構陣列。


Array Array(from: PackedStringArray)

PackedStringArray 建構陣列。


Array Array(from: PackedVector2Array)

PackedVector2Array 建構陣列。


Array Array(from: PackedVector3Array)

PackedVector3Array 建構陣列。


Array Array(from: PackedVector4Array)

PackedVector4Array 建構陣列。


方法說明

bool all(method: Callable) const 🔗

對陣列中的每個元素呼叫指定的 Callable。若該 Callable 對陣列中 所有 元素皆回傳 true,本方法便回傳 true;只要有任一元素回傳 false,就會回傳 false

method 必須接受一個 Variant 參數(目前的陣列元素)並回傳 bool

func greater_than_5(number):
    return number > 5

func _ready():
    print([6, 10, 6].all(greater_than_5)) # 印出 true(3/3 個元素為 true)
    print([4, 10, 4].all(greater_than_5)) # 印出 false(1/3 個元素為 true)
    print([4, 4, 4].all(greater_than_5))  # 印出 false(0/3 個元素為 true)
    print([].all(greater_than_5))         # 印出 true(0/0 個元素為 true)

    # 與上方第一行相同,但以 Lambda 撰寫。
    print([6, 10, 6].all(func(element): return element > 5)) # 印出 true

另請參閱 any()filter()map()reduce()

注意:與依賴 filter() 回傳陣列大小的作法不同,此方法會在第一時間就結束,以提升效能(大量陣列尤然)。

注意:對空陣列來說,此方法永遠回傳 true


bool any(method: Callable) const 🔗

對陣列中的每個元素呼叫指定的 Callable。若該 Callable 對陣列中 至少一個 元素回傳 true,本方法便回傳 true;若所有元素皆回傳 false,則回傳 false

method 必須接受一個 Variant 參數(目前的陣列元素)並回傳 bool

func greater_than_5(number):
    return number > 5

func _ready():
    print([6, 10, 6].any(greater_than_5)) # 印出 true(3 個元素為 true)
    print([4, 10, 4].any(greater_than_5)) # 印出 true(1 個元素為 true)
    print([4, 4, 4].any(greater_than_5))  # 印出 false(0 個元素為 true)
    print([].any(greater_than_5))         # 印出 false(0 個元素為 true)

    # 與上方第一行相同,但以 Lambda 撰寫。
    print([6, 10, 6].any(func(number): return number > 5)) # 印出 true

另請參閱 all()filter()map()reduce()

注意:與依賴 filter() 回傳陣列大小的作法不同,此方法會在第一時間就結束,以提升效能(大量陣列尤然)。

注意:對空陣列來說,本方法一律回傳 false


void append(value: Variant) 🔗

於陣列尾端附加 valuepush_back() 的別名)。


void append_array(array: Array) 🔗

將另一個 array 追加到本陣列尾端。

var numbers = [1, 2, 3]
var extra = [4, 5, 6]
numbers.append_array(extra)
print(numbers) # 印出 [1, 2, 3, 4, 5, 6]

void assign(array: Array) 🔗

將另一個 array 的元素指派至此陣列,並自動調整大小以符合 array。若此陣列已有型別限制,則會自動執行型別轉換。


Variant back() const 🔗

回傳陣列最後一個元素。若陣列為空,則失敗並回傳 null。另見 front()

注意:與直接使用 array[-1] 取值不同,若陣列為空,這個方法只會產生錯誤訊息,不會中斷專案執行。


int bsearch(value: Variant, before: bool = true) const 🔗

回傳已排序陣列中 value 的索引;若找不到,則回傳 value 應插入的位置以維持排序。內部演算法使用二分搜尋

beforetrue(預設),則傳回的索引會位於陣列中所有與 value 相等元素之前。

var numbers = [2, 4, 8, 10]
var idx = numbers.bsearch(7)
numbers.insert(idx, 7)
print(numbers) # 印出 [2, 4, 7, 8, 10]

var fruits = ["Apple", "Lemon", "Lemon", "Orange"]
print(fruits.bsearch("Lemon", true))  # 印出 1,指向第一個 "Lemon"
print(fruits.bsearch("Lemon", false)) # 印出 3,指向 "Orange"

注意:未排序的陣列上呼叫 bsearch() 會得到不可預期的結果,請先使用 sort()


int bsearch_custom(value: Variant, func: Callable, before: bool = true) const 🔗

回傳已排序陣列中 value 的索引;若找不到,則使用自訂比較函式 func 計算 value 應插入的位置以維持排序。內部演算法同樣為二分搜尋

func 的呼叫方式與 sort_custom() 相同,每次會傳入一個陣列元素與 value 供比較;若該陣列元素應位於 value之後則回傳 true,否則回傳 false

beforetrue(預設),傳回索引會位於所有與 value 相等之元素之前。

func sort_by_amount(a, b):
    return a[1] < b[1]

func _ready():
    var my_items = [["Tomato", 2], ["Kiwi", 5], ["Rice", 9]]
    var apple  = ["Apple", 5]
    var banana = ["Banana", 5]
    my_items.insert(my_items.bsearch_custom(apple,  sort_by_amount, true),  apple)  # 插入 Apple 於 Kiwi 之前
    my_items.insert(my_items.bsearch_custom(banana, sort_by_amount, false), banana) # 插入 Banana 於 Kiwi 之後
    print(my_items) # 印出 [["Tomato", 2], ["Apple", 5], ["Kiwi", 5], ["Banana", 5], ["Rice", 9]]

注意:未排序的陣列上呼叫 bsearch_custom() 會得到不可預期的結果,請先搭配 sort_custom() 使用。


void clear() 🔗

清除陣列的所有元素;等同於呼叫 resize() 並將大小設為 0


int count(value: Variant) const 🔗

回傳指定元素在陣列中出現的次數。

若需要統計符合條件的元素數量,可使用 reduce() 來實作。


Array duplicate(deep: bool = false) const 🔗

回傳此陣列的複製品。

預設為淺層複製:巢狀的 ArrayDictionaryResource 皆與原陣列共用;因此在其中一份內修改這些巢狀物件會同時影響另一份。

若將 deep 設為 true,則會進行深層複製:巢狀陣列與字典都會被遞迴複製。但 Resource 依然是共用的。


Array duplicate_deep(deep_subresources_mode: int = 1) const 🔗

Duplicates this array, deeply, like duplicate() when passing true, with extra control over how subresources are handled.

deep_subresources_mode must be one of the values from DeepDuplicateMode. By default, only internal resources will be duplicated (recursively).


void erase(value: Variant) 🔗

尋找並移除陣列中第一個與 value 相符的元素;若不存在則不做任何事。若要依索引移除元素,請改用 remove_at()

注意:此方法會將被移除位置之後的所有元素索引往前平移,在大型陣列上可能造成明顯開銷。

注意:在迴圈遍歷陣列時同時移除元素並不被支援,可能導致不可預期的行為。


void fill(value: Variant) 🔗

將陣列中的所有元素皆設成指定的 value

常與 resize() 搭配,用於建立指定大小並已初始化的陣列:

var array = []
array.resize(5)
array.fill(2)
print(array) # 印出 [2, 2, 2, 2, 2]

注意:value 為參照型別(衍生自 ObjectArrayDictionary…),整個陣列將會持有同一個物件的參照,而非複本。


Array filter(method: Callable) const 🔗

對陣列中的每個元素呼叫指定的 Callable,並依其回傳值產生新的過濾後陣列。

method 會收到一個陣列元素,當其回傳 true 時該元素會被保留;回傳 false 時則被排除。

func is_even(number):
    return number % 2 == 0

func _ready():
    print([1, 4, 5, 8].filter(is_even)) # 印出 [4, 8]

    # 與上例相同,但以 Lambda 撰寫。
    print([1, 4, 5, 8].filter(func(number): return number % 2 == 0))

另請參閱 any()all()map()reduce()


int find(what: Variant, from: int = 0) const 🔗

回傳 what 在陣列中第一次出現的索引;若不存在則回傳 -1。可以用 from 指定起始索引,搜尋將持續到陣列結尾。

注意:若只想知道陣列是否包含 what,可使用 has()(C# 中為 Contains),或在 GDScript 使用 in 運算子。

注意:基於效能考量,搜尋行為會受 whatVariant.Type 影響,例如 7(int)與 7.0(float)在此方法裡並不相等。


int find_custom(method: Callable, from: int = 0) const 🔗

Returns the index of the first element in the array that causes method to return true, or -1 if there are none. The search's start can be specified with from, continuing to the end of the array.

method is a callable that takes an element of the array, and returns a bool.

Note: If you just want to know whether the array contains anything that satisfies method, use any().

func is_even(number):
    return number % 2 == 0

func _ready():
    print([1, 3, 4, 7].find_custom(is_even.bind())) # Prints 2

# Another example using `bind()` to pass an additional parameter:
func is_specific_number(number, expected):
    return number == expected

func _ready():
    print([1, 3, 4, 7].find_custom(is_specific_number.bind(4))) # Prints 2

Variant front() const 🔗

回傳陣列第一個元素。若陣列為空則失敗並回傳 null。另見 back()

注意:與直接使用 array[0] 取值不同,若陣列為空,此方法僅會產生錯誤訊息而不會中斷專案執行。


Variant get(index: int) const 🔗

Returns the element at the given index in the array. If index is out-of-bounds or negative, this method fails and returns null.

This method is similar (but not identical) to the [] operator. Most notably, when this method fails, it doesn't pause project execution if run from the editor.


int get_typed_builtin() const 🔗

回傳此型別化陣列的內建 Variant 型別,為 Variant.Type 常數。若陣列未設定型別,則回傳 @GlobalScope.TYPE_NIL。另見 is_typed()


StringName get_typed_class_name() const 🔗

若此型別化陣列的內建 Variant 型別為 @GlobalScope.TYPE_OBJECT,則回傳其內建類別名稱,否則回傳空的 StringName。另見 is_typed()Object.get_class()


Variant get_typed_script() const 🔗

回傳與此型別化陣列關聯的 Script 實例;若不存在則為 null。另見 is_typed()


bool has(value: Variant) const 🔗

若陣列中包含指定的 value 則回傳 true

print(["inside", 7].has("inside"))  # 印出 true
print(["inside", 7].has("outside")) # 印出 false
print(["inside", 7].has(7))          # 印出 true
print(["inside", 7].has("7"))        # 印出 false

在 GDScript 中,也可使用 in 運算子:

if 4 in [2, 4, 6, 8]:
    print("4 is here!")

注意:基於效能考量,搜尋行為會受 valueVariant.Type 影響,例如 7(int)與 7.0(float)在此方法裡並不相等。


int hash() const 🔗

Returns a hashed 32-bit integer value representing the array and its contents.

Note: Arrays with equal hash values are not guaranteed to be the same, as a result of hash collisions. On the contrary, arrays with different hash values are guaranteed to be different.


int insert(position: int, value: Variant) 🔗

在索引 position 處插入新元素 (value)。合法範圍為 0 到陣列 size() 之間;若為負值則代表自陣列尾端反向計數。

成功時回傳 @GlobalScope.OK;失敗時則回傳其他 Error 常數。

注意:插入後,position 之後的所有元素索引都需往後平移,對大型陣列可能造成明顯效能成本。


bool is_empty() const 🔗

若陣列為空([])則回傳 true。另見 size()


bool is_read_only() const 🔗

若陣列為唯讀狀態則回傳 true。請參考 make_read_only()

在 GDScript 中,使用 const 宣告的陣列會自動成為唯讀。


bool is_same_typed(array: Array) const 🔗

若此陣列與指定的 array 具備相同型別限制則回傳 true。另見 is_typed()


bool is_typed() const 🔗

若陣列已設定型別限制則回傳 true。型別化陣列僅能包含指定型別的元素,但其方法仍預期回傳通用的 Variant

在 GDScript 中,可透過靜態型別語法建立型別化陣列:

var numbers: Array[float] = [0.2, 4.2, -2.0]
print(numbers.is_typed()) # 印出 true

void make_read_only() 🔗

將此陣列設為唯讀,之後無法改變元素值或調整順序。此設定不會遞迴套用至巢狀物件(例如字典)。

在 GDScript 中,使用 const 宣告的陣列預設即為唯讀。


Array map(method: Callable) const 🔗

對陣列中的每個元素呼叫指定的 Callable,並以其回傳值產生新陣列。

method 必須接受一個 Variant 參數(目前的陣列元素),並可回傳任何型別的 Variant

func double(number):
    return number * 2

func _ready():
    print([1, 2, 3].map(double)) # 印出 [2, 4, 6]

    # 與上例相同,但以 Lambda 撰寫。
    print([1, 2, 3].map(func(element): return element * 2))

另請參閱 filter()reduce()any()all()


Variant max() const 🔗

若陣列中的所有元素皆可比較,則回傳其中的最大值;否則回傳 null。另見 min()

若需透過自訂比較器尋找最大值,可使用 reduce()


Variant min() const 🔗

若陣列中的所有元素皆可比較,則回傳其中的最小值;否則回傳 null。另見 max()


Variant pick_random() const 🔗

自陣列中隨機回傳一個元素。若陣列為空,將產生錯誤並回傳 null

# 可能印出 1、2、3.25 或 "Hi"。
print([1, 2, 3.25, "Hi"].pick_random())

注意:與引擎中其他隨機函式(如 @GlobalScope.randi()shuffle())相同,本方法使用全域亂數種子。若需可預期的結果,請參考 @GlobalScope.seed()


Variant pop_at(position: int) 🔗

移除並回傳索引為 position 的元素。若 position 為負值,則自陣列尾端反向計算。若陣列為空則回傳 null;若索引越界,則同時輸出錯誤訊息。

注意:移除後,position 之後的所有元素索引都需往前平移,在大型陣列上可能造成明顯效能成本。


Variant pop_back() 🔗

移除並回傳陣列最後一個元素。若陣列為空則回傳 null 而不產生錯誤。另見 pop_front()


Variant pop_front() 🔗

移除並回傳陣列第一個元素。若陣列為空則回傳 null 而不產生錯誤。另見 pop_back()

注意:此方法會將其餘元素索引往前平移,對大型陣列可能產生明顯效能成本。


void push_back(value: Variant) 🔗

將元素追加於陣列尾端。另見 push_front()


void push_front(value: Variant) 🔗

於陣列開頭插入一個元素。另見 push_back()

注意:插入後其餘元素索引將往後平移,對大型陣列可能產生明顯效能成本。


Variant reduce(method: Callable, accum: Variant = null) const 🔗

對陣列中的每個元素呼叫指定的 Callable,以 accum 累計並於結束後回傳。

method 會接收兩個參數:目前的累計值 accum 與目前元素。若 accumnull(預設),則從第二個元素開始迴圈,並以第一個元素做為初始值。

func sum(accum, number):
    return accum + number

func _ready():
    print([1, 2, 3].reduce(sum, 0))  # 印出 6
    print([1, 2, 3].reduce(sum, 10)) # 印出 16

    # 與上例相同,但以 Lambda 撰寫。
    print([1, 2, 3].reduce(func(accum, number): return accum + number, 10))

除了可取代 max() 自訂比較器外,也能用來計算符合條件的元素數量(類似 count()):

func is_even(number):
    return number % 2 == 0

func _ready():
    var arr = [1, 2, 3, 4, 5]
    var even_count = arr.reduce(func(count, next): return count + 1 if is_even(next) else count, 0)
    print(even_count) # 印出 2

另請參閱 map()filter()any()all()


void remove_at(position: int) 🔗

Removes the element from the array at the given index (position). If the index is out of bounds, this method fails. If the index is negative, position is considered relative to the end of the array.

If you need to return the removed element, use pop_at(). To remove an element by value, use erase() instead.

Note: This method shifts every element's index after position back, which may have a noticeable performance cost, especially on larger arrays.


int resize(size: int) 🔗

將陣列長度設為 size。若新大小小於目前大小,尾端元素會被移除;若大於目前大小,則依陣列型別新增預設值(通常為 null)。

成功時回傳 @GlobalScope.OK。若失敗則可能回傳:陣列唯讀時為 @GlobalScope.ERR_LOCKEDsize 為負值時為 @GlobalScope.ERR_INVALID_PARAMETER;記憶體配置失敗時為 @GlobalScope.ERR_OUT_OF_MEMORY。可使用 size() 取得實際大小。

注意:一次呼叫本方法並批次指定新值,效能優於逐一 append() 新元素。


void reverse() 🔗

將陣列元素順序反轉。


int rfind(what: Variant, from: int = -1) const 🔗

回傳 what 在陣列中最後一次出現的索引;若不存在則回傳 -1。可使用 from 指定搜尋起點,搜尋方向會往陣列開頭進行。本方法與 find() 相反。


int rfind_custom(method: Callable, from: int = -1) const 🔗

回傳陣列中最後一個令 method 回傳 true 的元素索引;若無則回傳 -1。可用 from 指定搜尋起點,搜尋方向會往陣列開頭進行。本方法與 find_custom() 相反。


void set(index: int, value: Variant) 🔗

將索引為 index 的元素設為 value。此操作不會改變陣列大小,只會覆寫既有索引的值;效果與使用 array[index] = value 相同。


void shuffle() 🔗

將陣列元素隨機重新排列。

注意:與引擎中其他隨機函式(如 @GlobalScope.randi()pick_random())相同,本方法使用全域亂數種子。若需可預期的結果,請參考 @GlobalScope.seed()


int size() const 🔗

回傳陣列元素數量。空陣列([])一律回傳 0。另見 is_empty()


Array slice(begin: int, end: int = 2147483647, step: int = 1, deep: bool = false) const 🔗

回傳此陣列的切片新陣列,範圍從索引 begin(含)到 end(不含),並以 step 為間隔選取元素。

beginend 為負值,則視為自陣列尾端反向計數。

step 為負值,切片方向將反轉,且 begin 必須大於 end 才能正常運作。

若將 deep 設為 true,切片中的巢狀 ArrayDictionary 會被遞迴複製;詳見 duplicate()

var letters = ["A", "B", "C", "D", "E", "F"]
print(letters.slice(0, 2))   # 印出 ["A", "B"]
print(letters.slice(2, -2))  # 印出 ["C", "D"]
print(letters.slice(-2, 6))  # 印出 ["E", "F"]
print(letters.slice(0, 6, 2))  # 印出 ["A", "C", "E"]
print(letters.slice(4, 1, -1)) # 印出 ["E", "D", "C"]

void sort() 🔗

將陣列依遞增順序排序,排序結果取決於元素之間的「小於」(<) 比較。

var numbers = [10, 5, 2.5, 8]
numbers.sort()
print(numbers) # 印出 [2.5, 5, 8, 10]

注意:此排序演算法並非穩定排序,等值元素(如 22.0)的相對順序可能改變。


void sort_custom(func: Callable) 🔗

使用自訂 Callable 進行排序。

func 會在需要時多次被呼叫,並傳入兩個陣列元素作比較;若第一個元素應位於第二個元素之前則回傳 true,否則回傳 false

func sort_ascending(a, b):
    return a[1] < b[1]

func _ready():
    var my_items = [["Tomato", 5], ["Apple", 9], ["Rice", 4]]
    my_items.sort_custom(sort_ascending)
    print(my_items) # 印出 [["Rice", 4], ["Tomato", 5], ["Apple", 9]]

    # 使用 Lambda 以遞減排序。
    my_items.sort_custom(func(a, b): return a[1] > b[1])
    print(my_items) # 印出 [["Apple", 9], ["Tomato", 5], ["Rice", 4]]

若需照人類自然排序比較字串,可搭配 String.naturalnocasecmp_to()

var files = ["newfile1", "newfile2", "newfile10", "newfile11"]
files.sort_custom(func(a, b): return a.naturalnocasecmp_to(b) < 0)
print(files) # 印出 ["newfile1", "newfile2", "newfile10", "newfile11"]

注意:C# 不支援此方法。

注意:此排序演算法並非穩定排序,等值元素的相對順序可能改變。

注意:請勿讓 func 的回傳值隨機變動,否則 heapsort 需要的一致性將被破壞並導致不可預期結果。


運算子說明

bool operator !=(right: Array) 🔗

若本陣列的大小或元素與 right 不同則回傳 true


Array operator +(right: Array) 🔗

將右運算元 right 追加至左運算元,產生新的 Array(亦即陣列串接)。

var array1 = ["One", 2]
var array2 = [3, "Four"]
print(array1 + array2) # 印出 ["One", 2, 3, "Four"]

注意:對既有陣列,就地呼叫 append_array() 的效率遠高於使用 += 串接並重新指派。


bool operator <(right: Array) 🔗

依序比較兩個陣列的元素(由索引 0 開始,直到兩陣列共同的最後一個索引)。若某對元素首次出現差異,當本陣列元素小於 right 的元素時回傳 true,反之回傳 false;若元素相等則繼續比較下一對。

若所有比較過的元素皆相等,則比較陣列長度:若本陣列長度小於 right,回傳 true;否則回傳 false


bool operator <=(right: Array) 🔗

依序比較兩陣列元素。若本陣列元素第一次出現小於 right 的情況,立即回傳 true;若大於則回傳 false;相等則繼續比較。

若全部比較結果皆相等,則比較陣列長度:若本陣列長度小於或等於 right,回傳 true,否則回傳 false


bool operator ==(right: Array) 🔗

比較左右兩個陣列。若大小與內容皆相同則回傳 true,否則回傳 false


bool operator >(right: Array) 🔗

依序比較兩陣列元素。若本陣列元素第一次出現大於 right 的情況,立即回傳 true;若小於則回傳 false;相等則繼續比較。

若全部比較結果皆相等,則比較陣列長度:若本陣列長度大於 right,回傳 true,否則回傳 false


bool operator >=(right: Array) 🔗

依序比較兩陣列元素。若本陣列元素第一次出現大於 right 的情況,立即回傳 true;若小於則回傳 false;相等則繼續比較。

若全部比較結果皆相等,則比較陣列長度:若本陣列長度大於或等於 right,回傳 true,否則回傳 false


Variant operator [](index: int) 🔗

回傳位於 indexVariant 元素,索引自 0 起算。若 index 大於等於 0,則自陣列開頭計算;若為負值,則自陣列尾端反向計算。若索引越界,將於執行階段產生錯誤,並在編輯器中中斷專案執行。