From b738a52e3592007a568f0ab92c434acc455dfb1f Mon Sep 17 00:00:00 2001 From: Simon Wachter Date: Thu, 19 Jan 2023 13:16:48 +0100 Subject: [PATCH] escape table keys that map to lua keywords (#59) --- inspect.lua | 29 ++++++++++++++++++++++++++++- inspect.tl | 29 ++++++++++++++++++++++++++++- spec/inspect_spec.lua | 7 +++++++ 3 files changed, 63 insertions(+), 2 deletions(-) diff --git a/inspect.lua b/inspect.lua index f8d69dc..400229f 100644 --- a/inspect.lua +++ b/inspect.lua @@ -87,8 +87,35 @@ local function escape(str) "%c", shortControlCharEscapes)) end +local luaKeywords = { + ['and'] = true, + ['break'] = true, + ['do'] = true, + ['else'] = true, + ['elseif'] = true, + ['end'] = true, + ['false'] = true, + ['for'] = true, + ['function'] = true, + ['goto'] = true, + ['if'] = true, + ['in'] = true, + ['local'] = true, + ['nil'] = true, + ['not'] = true, + ['or'] = true, + ['repeat'] = true, + ['return'] = true, + ['then'] = true, + ['true'] = true, + ['until'] = true, + ['while'] = true, +} + local function isIdentifier(str) - return type(str) == "string" and not not str:match("^[_%a][_%a%d]*$") + return type(str) == "string" and + not not str:match("^[_%a][_%a%d]*$") and + not luaKeywords[str] end local flr = math.floor diff --git a/inspect.tl b/inspect.tl index 7ac64c8..78b52e1 100644 --- a/inspect.tl +++ b/inspect.tl @@ -87,8 +87,35 @@ local function escape(str: string): string "%c", shortControlCharEscapes)) end +local luaKeywords: {string:boolean} = { + ['and'] = true, + ['break'] = true, + ['do'] = true, + ['else'] = true, + ['elseif'] = true, + ['end'] = true, + ['false'] = true, + ['for'] = true, + ['function'] = true, + ['goto'] = true, + ['if'] = true, + ['in'] = true, + ['local'] = true, + ['nil'] = true, + ['not'] = true, + ['or'] = true, + ['repeat'] = true, + ['return'] = true, + ['then'] = true, + ['true'] = true, + ['until'] = true, + ['while'] = true, +} + local function isIdentifier(str: any): boolean - return str is string and not not str:match("^[_%a][_%a%d]*$") + return str is string + and not not str:match("^[_%a][_%a%d]*$") + and not luaKeywords[str] end local flr = math.floor diff --git a/spec/inspect_spec.lua b/spec/inspect_spec.lua index a6ddd00..bcdb122 100644 --- a/spec/inspect_spec.lua +++ b/spec/inspect_spec.lua @@ -111,6 +111,13 @@ describe( 'inspect', function() end) end + it('escapes string keys that are not valid identifiers', function() + assert.equals(unindent([[{ + ["if"] = true, + ["key with spaces"] = true + }]]), inspect({['if'] = true, ['key with spaces'] = true})) + end) + it('works with simple dictionary tables', function() assert.equals("{\n a = 1,\n b = 2\n}", inspect({a = 1, b = 2})) end)