Skip to content

Commit b738a52

Browse files
authored
escape table keys that map to lua keywords (#59)
1 parent bac5932 commit b738a52

File tree

3 files changed

+63
-2
lines changed

3 files changed

+63
-2
lines changed

inspect.lua

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -87,8 +87,35 @@ local function escape(str)
8787
"%c", shortControlCharEscapes))
8888
end
8989

90+
local luaKeywords = {
91+
['and'] = true,
92+
['break'] = true,
93+
['do'] = true,
94+
['else'] = true,
95+
['elseif'] = true,
96+
['end'] = true,
97+
['false'] = true,
98+
['for'] = true,
99+
['function'] = true,
100+
['goto'] = true,
101+
['if'] = true,
102+
['in'] = true,
103+
['local'] = true,
104+
['nil'] = true,
105+
['not'] = true,
106+
['or'] = true,
107+
['repeat'] = true,
108+
['return'] = true,
109+
['then'] = true,
110+
['true'] = true,
111+
['until'] = true,
112+
['while'] = true,
113+
}
114+
90115
local function isIdentifier(str)
91-
return type(str) == "string" and not not str:match("^[_%a][_%a%d]*$")
116+
return type(str) == "string" and
117+
not not str:match("^[_%a][_%a%d]*$") and
118+
not luaKeywords[str]
92119
end
93120

94121
local flr = math.floor

inspect.tl

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -87,8 +87,35 @@ local function escape(str: string): string
8787
"%c", shortControlCharEscapes))
8888
end
8989

90+
local luaKeywords: {string:boolean} = {
91+
['and'] = true,
92+
['break'] = true,
93+
['do'] = true,
94+
['else'] = true,
95+
['elseif'] = true,
96+
['end'] = true,
97+
['false'] = true,
98+
['for'] = true,
99+
['function'] = true,
100+
['goto'] = true,
101+
['if'] = true,
102+
['in'] = true,
103+
['local'] = true,
104+
['nil'] = true,
105+
['not'] = true,
106+
['or'] = true,
107+
['repeat'] = true,
108+
['return'] = true,
109+
['then'] = true,
110+
['true'] = true,
111+
['until'] = true,
112+
['while'] = true,
113+
}
114+
90115
local function isIdentifier(str: any): boolean
91-
return str is string and not not str:match("^[_%a][_%a%d]*$")
116+
return str is string
117+
and not not str:match("^[_%a][_%a%d]*$")
118+
and not luaKeywords[str]
92119
end
93120

94121
local flr = math.floor

spec/inspect_spec.lua

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,13 @@ describe( 'inspect', function()
111111
end)
112112
end
113113

114+
it('escapes string keys that are not valid identifiers', function()
115+
assert.equals(unindent([[{
116+
["if"] = true,
117+
["key with spaces"] = true
118+
}]]), inspect({['if'] = true, ['key with spaces'] = true}))
119+
end)
120+
114121
it('works with simple dictionary tables', function()
115122
assert.equals("{\n a = 1,\n b = 2\n}", inspect({a = 1, b = 2}))
116123
end)

0 commit comments

Comments
 (0)