query
On this page

toLua

lib.generators.toLua

Docs pulled from | This Revision | about 1 hour ago


Translate a simple Nix expression to Lua representation with occasional Lua-inlines that can be constructed by mkLuaInline function.

Configuration:

  • multiline - by default is true which results in indented block-like view.
  • indent - initial indent.
  • asBindings - by default generate single value, but with this use attrset to set global vars.

Attention:

Regardless of multiline parameter there is no trailing newline.

Inputs

Structured function argument
multiline (optional, default: true)
If this option is true, the output is indented with newlines for attribute sets and lists
indent (optional, default: "")
Initial indentation level
asBindings (optional, default: false)
Interpret as variable bindings
Value

The value to be converted to Lua

Type

toLua :: AttrSet -> Any -> String

Examples

lib.generators.toLua usage example

generators.toLua {}
  {
    cmd = [ "typescript-language-server" "--stdio" ];
    settings.workspace.library = mkLuaInline ''vim.api.nvim_get_runtime_file("", true)'';
  }
->
 {
   ["cmd"] = {
     "typescript-language-server",
     "--stdio"
   },
   ["settings"] = {
     ["workspace"] = {
       ["library"] = (vim.api.nvim_get_runtime_file("", true))
     }
   }
 }

Noogle detected

Implementation

The following is the current implementation of this function.

toLua = {
    multiline ? true,
    indent ? "",
    asBindings ? false,
  }@args: v:
    let
      innerIndent = "${indent}  ";
      introSpace = if multiline then "\n${innerIndent}" else " ";
      outroSpace = if multiline then "\n${indent}" else " ";
      innerArgs = args // {
        indent = if asBindings then indent else innerIndent;
        asBindings = false;
      };
      concatItems = concatStringsSep ",${introSpace}";
      isLuaInline = { _type ? null, ... }: _type == "lua-inline";

      generatedBindings =
          assert assertMsg (badVarNames == []) "Bad Lua var names: ${toPretty {} badVarNames}";
          concatStrings (
            mapAttrsToList (key: value: "${indent}${key} = ${toLua innerArgs value}\n") v
            );

      # https://en.wikibooks.org/wiki/Lua_Programming/variable#Variable_names
      matchVarName = match "[[:alpha:]_][[:alnum:]_]*(\\.[[:alpha:]_][[:alnum:]_]*)*";
      badVarNames = filter (name: matchVarName name == null) (attrNames v);
    in
    if asBindings then
      generatedBindings
    else if v == null then
      "nil"
    else if isInt v || isFloat v || isString v || isBool v then
      toJSON v
    else if isPath v || isDerivation v then
      toJSON "${v}"
    else if isList v then
      (if v == [ ] then "{}" else
      "{${introSpace}${concatItems (map (value: "${toLua innerArgs value}") v)}${outroSpace}}")
    else if isAttrs v then
      (
        if isLuaInline v then
          "(${v.expr})"
        else if v == { } then
          "{}"
        else
          "{${introSpace}${concatItems (
            mapAttrsToList (key: value: "[${toJSON key}] = ${toLua innerArgs value}") v
            )}${outroSpace}}"
      )
    else
      abort "generators.toLua: type ${typeOf v} is unsupported";