---
name: tql_emit
kind: function
lang: cpp
domain: core
version: "1.0.0"
purity: pure
signature: "std::string tql::emit(const data_table::State& state, const std::vector<std::string>& headers, const std::vector<data_table::ColumnType>& types)"
description: "Serializes a data_table::State to a complete TQL v1 Lua chunk. TQL (Table Query Language) is the canonical textual format for State round-trips: emit produces text, tql_apply parses it back."
tags: [tables, tql, serialization, cpp-tables]
uses_functions: []
uses_types:
  - data_table_types_cpp_core
returns: []
returns_optional: false
error_type: ""
imports:
  - "core/tql_emit.h"
  - "core/tql_helpers.h"
tested: true
tests:
  - "emit empty state produces valid header"
  - "emit single column"
  - "emit state with filter in stage 0"
  - "emit state with sort"
  - "emit stage 1 with breakout + aggregation"
  - "emit with color rule"
  - "emit with viz panel"
  - "emit join"
  - "lua_string_literal escaping"
  - "color roundtrip"
test_file_path: "cpp/functions/core/tql_emit_test.cpp"
file_path: "cpp/functions/core/tql_emit.cpp"
params:
  - name: state
    desc: "Current view/pipeline State to serialize (stages, col_visible, col_order, color_rules, joins, extra_panels)."
  - name: headers
    desc: "Original column names (orig_cols count). Derived columns are taken from state.stages[0].derived automatically."
  - name: types
    desc: "Column types for original columns. Missing entries default to ColumnType::Auto."
output: "UTF-8 Lua chunk starting with a comment header and ending with return { version=1, display, main_source?, joins?, stages, columns, views, visualization_settings }. Self-contained and parseable with tql_apply."
---

## Ejemplo

```cpp
#include "core/tql_emit.h"

data_table::State st;
st.stages.push_back(data_table::Stage{});
st.stages[0].filters.push_back({0, data_table::Op::Eq, "Alice"});
st.display = data_table::ViewMode::Table;

std::vector<std::string> headers = {"name", "age"};
std::vector<data_table::ColumnType> types = {
    data_table::ColumnType::String,
    data_table::ColumnType::Int
};

std::string lua_chunk = tql::emit(st, headers, types);
// lua_chunk starts with "-- TQL v1 ..." and is parseable by tql_apply
```

## Cuando usarla

Cuando necesites persistir o serializar el estado de una tabla TQL (filtros, sorts, breakouts, viz config) a texto. Úsala antes de guardar en BD, copiar al portapapeles, o enviar al servidor. Para recuperar el State usa `tql_apply`.

## Notas

- Función pura: no usa I/O, no Lua runtime, no ImGui.
- Los DerivedColumn con formula no vacía se emiten en la sección `expressions`. Los de `source_col >= 0` (retipados puros) se emiten como columnas en la sección `columns` pero sin entrada en `expressions`.
- El formato TQL es texto Lua que usa `return { ... }` como raíz — parseable con `luaL_loadbufferx` + `lua_pcall`.
- Promoted from `cpp/apps/primitives_gallery/playground/tables/tql.cpp`, issue 0081-C.
