_draw() not working?

Godot Version

Godot 4.2.1

Question

the _draw function is not working in my project, and I have no clue why. this code is supposed to draw a 50 by 50 grid of tiles, but it’s not, I get the error:

E 0:00:00:0822 MapDrawer.gd:19 @ _draw(): Drawing is only allowed inside NOTIFICATION_DRAW, _draw() function or ‘draw’ signal.
<C++ Error> Condition “!drawing” is true.
<C++ Source> scene/main/canvas_item.cpp:673 @ draw_rect()
MapDrawer.gd:19 @ _draw()
MapDrawer.gd:12 @ _ready()

here is my code:

extends Control

var map_size = Vector2(50, 50)
var tile_size = Vector2(20, 20)

func _ready():
	for y in range(0, map_size.y):
		for x in range(0, map_size.x):
			position.x += tile_size.x
			_draw()
		position.x -= tile_size.x * map_size.x
		position.y += tile_size.y

func _draw():
	var col = Color(1, 0, 0)
	var rect = Rect2(position, Vector2(10,10))
	draw_rect(rect, col)

You seem to call _draw() from inside the _ready() function. That is not supported.
If you remove this explicit call, your script should no longer cause errors.

The overridden _draw() function is called automatically during each NOTIFICATION_DRAW.

You can find a few examples here: Custom drawing in 2D — Godot Engine (4.2) documentation in English

As Sauermann said, draw is automatically called. In the rare cases where it isn’t, you can manually trigger it by calling queue_redraw(). This will cause Godot to re-draw the canvas item at the next rendering pass.

What you put in _ready() should go in _draw() and instead of _draw() inside your for loop, you use draw_rect(), but also, instead of changing position use a local var.