escape table keys that map to lua keywords (#59)

This commit is contained in:
Simon Wachter 2023-01-19 13:16:48 +01:00 committed by GitHub
parent bac593278b
commit b738a52e35
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 63 additions and 2 deletions

View File

@ -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

View File

@ -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

View File

@ -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)