> For the complete documentation index, see [llms.txt](https://vala.gitbook.io/vala/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://vala.gitbook.io/vala/advanced-features/variable-length-arguments.md).

# Список аргументов переменной длины

Vala поддерживает список аргументов переменной длины в стиле С. Они объявляются с помощью многоточия в заголовке метода. Метод с переменным числом аргументов должен иметь хотя бы один фиксированный параметр:

```csharp
void method_with_varargs(int x, ...) {
    var l = va_list();
    string s = l.arg();
    int i = l.arg();
    stdout.printf("%s: %d\n", s, i);
}
```

Здесь х - фиксированный аргумент, нужен чтобы метод удовлетворял требованиям. Вы получаете список аргументов с помощью `va_list()`. Затем вы можете получить параметры один за другим с помощью обобщенного метода `arg<T>()`, где Т - это ожидаемый тип аргументов. Если тип, как в данном случае, легко может быть выяснен, то он будет выведен автоматически, и вам нужно вызывать лишь `arg()` без указания обобщенного типа.

Следующий пример делает разбор парных аргументов, имеющих типы string и double:

```csharp
void method_with_varargs(int fixed, ...) {
    var l = va_list();
    while (true) {
        string? key = l.arg();
        if (key == null) {
            break;  // конец списка
        }
        double val = l.arg();
        stdout.printf("%s: %g\n", key, val);
    }
}

void main() {
    method_with_varargs(42, "foo", 0.75, "bar", 0.25, "baz", 0.32);
}
```

Здесь проводится проверка на `null` для определения конца списка аргументов. Vala неявно передает методу нулевой элемент в конце списка аргументов, если они имеют переменную длину.

Аргументы переменного числа имеют серьезный недостаток: они не типо-безопасны. Компилятор не может сказать вам правильного ли типа аргументы вы передаете такому методу, поэтому у вас должны быть серьезные основания, чтобы их использовать, например: вы пишете функцию, по которой код на С будет обращаться к библиотеке Vala, или делаете биндинг к С коду. Часто массив в аргументах является лучшим выбором.

Общий паттерн при работе с аргументами переменного числа - это указывать аргументы парами строка-значение, обычно используются пары gobject свойство - значение. В таком случае вы можете написать как свойство : значение, т.е.:

```coffeescript
actor.animate (AnimationMode.EASE_OUT_BOUNCE, 3000, x: 100.0, y: 200.0, rotation_angle_z: 500.0, opacity: 0);
```

эквивалентен строке

```coffeescript
actor.animate (AnimationMode.EASE_OUT_BOUNCE, 3000, "x", 100.0, "y", 200.0, "rotation-angle-z", 500.0, "opacity", 0);
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://vala.gitbook.io/vala/advanced-features/variable-length-arguments.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
