godotengine / godot-proposals

Godot Improvement Proposals (GIPs)
MIT License
1.16k stars 97 forks source link

Array return values for better function chaining #8455

Open TheColorRed opened 11 months ago

TheColorRed commented 11 months ago

Describe the project you are working on

Game

Describe the problem or limitation you are having in your project

I like chaining array functions, so it would be helpful if more of the functions returned the changed array instead of void, also functions that already return something could have a sibling function that returns the array (not all functions this works for though).

Describe the feature / enhancement and how it helps to overcome the problem or limitation

In many cases, all that really would need to be done is return the reference to the array instead of returning void, and/or add an additional function that returns the reference.

Describe how your proposal will work, with code, pseudo-code, mock-ups, and/or diagrams

Here are some examples that are not possible (examples are stupefied for example purposes):

# An array filled with five random values:
var arr = Array(5).fill(randf() * 100)
var array1 = ['a', 'b', 'c']
  .concat(['d', 'e', 'f'])
  .concat(['g', 'h', 'i'])
  .filter(func(itm): return /* do something... */)

Here is an example of something I actually wanted to do which I had to use more lines because I couldn't concat:

var line2d: Line2D
var collision_shape: CollisionPolygon2D

# What I wanted to do:
func _make_shape():
  # concat: returns result of combining line2d points with its reversed value
  collision_shape.polygon = line2d.points.concat(line.2dpoints.reverse())

# What I actually had to do:
func _make_shape():
  var points2 := line2d.points.duplicate()
  points2.reverse()
  var new_points = []
  new_points.append_array(line2d.points)
  new_points.append_array(points2)
  collision_shape.polygon = new_points

List of proposed changes:

If this enhancement will not be used often, can it be worked around with a few lines of script?

Yeah, it just adds additional lines code at times. This just feels cleaner to me.

Is there a reason why this should be core and not an add-on in the asset library?

It modifies the array API of GDScript.

AThousandShips commented 11 months ago

Array(int) - Add ability to pass a number which would initiate an empty array filled with null for each value.

Already covered by:

miv391 commented 11 months ago

Some previous discussion about chaining: https://github.com/godotengine/godot-proposals/discussions/4025