> For the complete documentation index, see [llms.txt](https://docs.perfectcs2.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.perfectcs2.com/comecando/ciclo-de-vida.md).

# Ciclo de vida

O que acontece ao carregar, recarregar e parar um script.

## Carregar

Ao ligar um script, o Perfect cria um ambiente Lua só para ele e roda o arquivo de cima a baixo, uma vez. Nesse momento o script normalmente:

1. cria as opções do menu (`ui.*`);
2. registra funções que vão rodar depois (`callbacks.add`, `events.on`);
3. lê dados salvos (`storage.get`).

```lua
local enabled = ui.toggle("Enabled", "", true)   -- 1

callbacks.add("draw", function()                 -- 2: runs every frame
    if enabled:get() then render.text(10, 10, "hi", color()) end
end)

local loads = storage.get("loads", 0) + 1        -- 3
storage.set("loads", loads)
print("Loaded " .. loads .. " times")
```

Cada script tem o seu próprio ambiente: variáveis globais de um não aparecem nos outros.

## Enquanto roda

Depois de carregado, o script só volta a rodar quando algo chama uma das suas funções:

| Quando                           | Como registrar                                                       |
| -------------------------------- | -------------------------------------------------------------------- |
| A cada frame, para desenhar      | `callbacks.add("draw", fn)`                                          |
| A cada comando enviado ao jogo   | `callbacks.add("create_move", fn)`                                   |
| O menu abriu ou fechou           | `callbacks.add("menu_open", fn)` / `callbacks.add("menu_close", fn)` |
| Um evento do jogo, como uma kill | `events.on("player_death", fn)`                                      |
| Uma opção do script mudou        | `option:callback(fn)`                                                |
| Um botão do script foi clicado   | `ui.button(..., fn)`                                                 |
| Depois de um tempo               | `client.delay(seconds, fn)`                                          |

Veja [callbacks](/documentacao/callbacks.md) e [events](/documentacao/events.md).

## Descarregar

O script para quando você desliga o switch, recarrega ou fecha o Perfect. Antes de parar, os callbacks `"unload"` rodam:

```lua
callbacks.add("unload", function()
    menu.set("world.third_person", false) -- undo what the script changed
end)
```

Ao parar:

* as opções do script somem do menu;
* os callbacks deixam de rodar;
* as imagens carregadas são liberadas;
* os dados do `storage` são gravados.

## Erros

Um erro não tratado, ao carregar ou dentro de qualquer callback, para o script. Quando isso acontece:

* o script fica com status **Erro**;
* a primeira linha do erro aparece na lista, e uma notificação avisa;
* o **Console** mostra a mensagem completa, com o *stack traceback*;
* o editor marca a linha.

Para tratar um erro sem parar o script, use `pcall`:

```lua
local ok, err = pcall(function()
    -- code that may fail
end)
if not ok then warn("failed: " .. err) end
```

## Recarregar

**Recarregar**, ou **Salvar e recarregar** no editor, descarrega o script e carrega de novo do arquivo. Os valores das opções voltam aos padrões do código. Para manter um valor entre recargas, salve com [`storage`](/documentacao/api/storage.md).

Se o arquivo mudar no disco enquanto o script roda, ele aparece como **Alterado** na lista até ser recarregado.


---

# 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 by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.perfectcs2.com/comecando/ciclo-de-vida.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
