mirror of
https://github.com/kikito/inspect.lua.git
synced 2024-12-15 14:34:21 +00:00
escape table keys that map to lua keywords (#59)
This commit is contained in:
parent
bac593278b
commit
b738a52e35
29
inspect.lua
29
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
|
||||
|
29
inspect.tl
29
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
|
||||
|
@ -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)
|
||||
|
Loading…
Reference in New Issue
Block a user