diff options
author | Mykola Orliuk <virkony@gmail.com> | 2023-04-29 18:35:07 +0200 |
---|---|---|
committer | Mykola Orliuk <virkony@gmail.com> | 2023-04-29 19:26:35 +0200 |
commit | 7287c0e076c3fd69d55e96cdc5c46e951bed01d4 (patch) | |
tree | 0771cf865182ff9597e46f4a10b7805df1ff5a30 /lib/generators.nix | |
parent | 25f8a3f2763ac89f5124176627b22181d883a053 (diff) |
lib.generators.toLua: asBindings option
Allows to generate code block for setting of global variables
Diffstat (limited to 'lib/generators.nix')
-rw-r--r-- | lib/generators.nix | 24 |
1 files changed, 21 insertions, 3 deletions
diff --git a/lib/generators.nix b/lib/generators.nix index 4ecbdac3c125e..c46ecca58c68f 100644 --- a/lib/generators.nix +++ b/lib/generators.nix @@ -434,6 +434,7 @@ ${expr "" v} 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. @@ -464,18 +465,35 @@ ${expr "" v} /* If this option is true, the output is indented with newlines for attribute sets and lists */ multiline ? true, /* Initial indentation level */ - indent ? "" + indent ? "", + /* Interpret as variable bindings */ + asBindings ? false, }@args: v: with builtins; let innerIndent = "${indent} "; introSpace = if multiline then "\n${innerIndent}" else " "; outroSpace = if multiline then "\n${indent}" else " "; - innerArgs = args // { indent = innerIndent; }; + innerArgs = args // { + indent = if asBindings then indent else innerIndent; + asBindings = false; + }; concatItems = concatStringsSep ",${introSpace}"; isLuaInline = { _type ? null, ... }: _type == "lua-inline"; + + generatedBindings = + assert lib.assertMsg (badVarNames == []) "Bad Lua var names: ${toPretty {} badVarNames}"; + libStr.concatStrings ( + lib.attrsets.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 v == null then + if asBindings then + generatedBindings + else if v == null then "nil" else if isInt v || isFloat v || isString v || isBool v then builtins.toJSON v |