jujumumu
jujumumu

Reputation: 390

Godot - How do I create a subarray of a list in Gdscript?

I know it's possible to slice an array in python by array[2:4]. The way I get around this is to just loop through the indexes I want and append them to the new_list. This way requires more work is there just a simple way to do it like in python?

Upvotes: 7

Views: 7543

Answers (1)

Calinou
Calinou

Reputation: 949

You can use the Array.slice() method added in Godot 3.2 for this purpose:

Array slice ( int begin, int end, int step=1, bool deep=False )

Duplicates the subset described in the function and returns it in an array, deeply copying the array if deep is true. Lower and upper index are inclusive, with the step describing the change between indices while slicing.

Example:

var array = [2, 4, 6, 8]
var subset = array.slice(1, 2)
print(subset)  # Should print [4, 6]

Upvotes: 12

Related Questions