Compiler · language feature
Compute configuration once
Use ordinary Nelua functions to transform typed configuration into data that is already present in the generated program.
Compile-time evaluation (CTFE) is useful when a table, descriptor, protocol constant, or lookup structure follows from values known before the target runs. Keep the inputs as typed records, reuse them by name, and let the compiler emit the result as ordinary static C data.
Two ways to ask for evaluation
comptime(call) marks one call for evaluation. Marking a function <comptime> makes its calls compile-time calls, so all arguments must be known at those call sites. The annotation guarantees that the function is never emitted to C. An ordinary function evaluated through comptime may still be emitted to C even when the program has no runtime calls to it.
local function add_bias(value: integer, bias: integer): integer
return value + bias
end
local OFFSET = comptime(add_bias(10, 2)) -- folded value: 12
local function scale(value: integer, factor: integer): integer <comptime>
return value * factor
end
local GAIN = scale(6, 7) -- folded value: 42
assert(OFFSET == 12 and GAIN == 42)The function annotation guarantees scale is absent from generated C. add_bias can still be emitted even though this example has no runtime call to it.
Use explicit comptime(...) when only selected calls should be evaluated. Use the function annotation when compile-time execution is the function's contract and runtime arguments should be rejected.
Named record configs
A record constant gives a configuration a type and a stable name. It can be passed to multiple compile-time functions, and nested records and fixed arrays keep their types as data moves through the evaluator.
local Link = @record{baud: uint32, parity: uint8}
local RadioConfig = @record{
reference_hz: uint32,
link: Link,
divisors: [3]uint32,
}
local RADIO <comptime> = RadioConfig{
reference_hz = 32000000,
link = Link{baud = 9600}, -- omitted parity is zero
divisors = {9600, 19200, 38400},
}
local function make_rate_table(cfg: RadioConfig): [3]uint32 <comptime>
local rates: [3]uint32
for i: uint8 = 0, 2 do
rates[i] = cfg.reference_hz // cfg.divisors[i]
end
return rates
end
local RATES = comptime(make_rate_table(RADIO))
print(RATES[0], RATES[1], RATES[2]) -- 3333 1666 833
local DEFAULT_RADIO <comptime> = RadioConfig{}
-- Every field and array element omitted above is zero-initialized.The compiler evaluates make_rate_table using the fields of RADIO. The generated program contains the resulting three integers as static data; it does not call the table builder or calculate the entries on the target. The numbers are a teaching example of integer division, not a hardware clock prescription.
Nested values and mutation
Compile-time records and arrays behave as values. Assigning one copies it, including nested arrays and records. A function may update its local parameter copy while deriving an output, without changing the named input config or another caller's copy.
local Point = @record{x: integer, y: integer}
local Board = @record{origin: Point, cells: [2]Point}
local BOARD <comptime> = Board{
origin = {2, 3},
cells = {{4, 5}, {6}}, -- second point's y defaults to zero
}
local function summarize(board: Board): integer <comptime>
board.origin.x = board.origin.x + 1 -- edits this value copy
return board.origin.x * 100 + board.cells[0].y
end
local SUMMARY = comptime(summarize(BOARD)) -- 305
local AGAIN = comptime(summarize(BOARD)) -- also 305; BOARD is unchanged
assert(SUMMARY == 305 and AGAIN == 305)Omitted record fields and fixed-array elements receive the type's zero value. Config{...} supplies selected fields, while Config() creates a zero-initialized record. Positional and named fields follow normal record literal rules.
What reaches C
A folded scalar is a constant expression. An array or record result is emitted as a C initializer, so it has no runtime table-building loop, allocator, or evaluator support code. The current backend represents this fixed array with a generated C wrapper; its initializer contains the folded values:
static nluint32_arr3 RATES = { .v = { 3333U, 1666U, 833U } };The compiler's generated C is still compiled by your selected C compiler. CTFE removes the computation from the target program; it does not bypass the C compiler or turn a runtime input into a compile-time value.
A protocol-table pattern
Embedded code often repeats small transforms: deriving a packet mask from a field width, expanding a CRC polynomial into a lookup table, or calculating a set of candidate divisors from a declared clock and rate list. The same pattern applies to firmware, drivers, and protocol libraries: put the inputs in a typed config, write a deterministic Nelua function, then fold its result.
local PacketLayout = @record{
sequence_bits: uint8,
type_bits: uint8,
payload_bytes: uint16,
}
local LAYOUT <comptime> = PacketLayout{
sequence_bits = 12, type_bits = 4, payload_bytes = 256,
}
local function make_packet_mask(layout: PacketLayout): uint16 <comptime>
return (1 << layout.sequence_bits) - 1
end
local SEQUENCE_MASK = make_packet_mask(LAYOUT) -- folded at compile time: 4095
assert(SEQUENCE_MASK == 4095)
-- Runtime code can now pack/unpack using SEQUENCE_MASK and LAYOUT.payload_bytes.
-- The field widths and protocol interpretation remain your responsibility.This demonstrates calculation from protocol metadata only. It does not prescribe an on-wire layout, synchronization policy, peripheral register value, timing tolerance, or device-qualified formula; those must come from the relevant protocol or hardware documentation.
Caching and repeatability
Within one compilation, evaluator results are cached by function and canonicalized argument values. Repeating a pure call with the same config can reuse the result. This makes compile-time work predictable and avoids repeating expensive table construction. Inputs and outputs retain value semantics: cache reuse does not make a callee's mutations visible in the caller's config.
Keep CTFE functions deterministic. Compiler-side print output and errors belong to compilation, not the target program. The final folded values become part of generated C and therefore of the normal build artifacts.
Limits and diagnostics
CTFE is a bounded evaluator for Nelua values, not a second machine that runs the target program. It mirrors important C-facing numeric behavior: fixed-width integer wrapping, unsigned division, Nelua shift behavior, and float32 rounding. Floating-point transcendental functions may differ in the last digits from the target C library.
- Each evaluation is limited by
pragmas.comptime_steps(default 10 million Lua instructions) andpragmas.comptime_stack(default 10,000 nested calls). - Supported values include scalars, booleans, strings, enums, fixed arrays, and records composed of supported values. Nested records and arrays are supported.
- Pointers can be used as references while evaluating supported record/array values; CTFE does not dereference target addresses or execute against target memory. Records containing pointer fields are rejected.
- Optionals, variants, closures,
defer,for initerators, spans, dynamic containers, allocators, garbage collection, C imports, operating-system calls, and I/O are outside the current evaluator subset. Diagnostics identify unsupported operations when the function is evaluated. - Values read from outside the function must themselves be compile-time values. Arguments and results must use the supported value shapes; runtime data cannot be smuggled into a compile-time call.
A compile-time failure is a build failure. Keep generated tables small enough for the configured step and stack budgets, and test important numeric boundaries on the intended target toolchain as well.
Try it in a project
Put the code in a .nelua file, then compile and run it with the fork:
nelua radio_config.neluaTo inspect the generated C, run nelua --print-code radio_config.nelua > radio_config.c and search the output for the folded array. Check the fork's current CTFE reference for supported syntax and diagnostics.