A lua library completes data beautification output, and has no external dependencies.
Install
You can install the library with luarock, like this:
$ luarocks install pprintOr the file should dropped into a project or a lua lib, then require by it:
pprint = require('pprint')Also, using the library is very simple. It provides several functions:
-
pprint.pprint(obj, indent?, width?, depth?)Print the formatted representation of object with color to stream with a trailing newline.
indent: indent of each level
width: max col limit
depth: level limit of recursive
local test_struct = { ['name'] = 'Tom', age = 18, hobbys = { 'game', ['ball'] = {'football', 'basketball'} }, eat = function(food) print('I eat: ' .. food) end } pprint.pprint(test_struct)
-
pprint.pp(obj, args?)Print the formatted representation of object to stream with a trailing newline.
args: The options of function. Will be transparently transmitted to
PrettyPrinter. -
pprint.pformat(obj, indent?, width?, depth?)Return the formatted representation of object as a string.
indent: Number of spaces to indent for each level of nesting.
width: Attempted maximum number of columns in the output.
depth: Depth limit, exceeding the limit will be folded.
-
pprint.isrecursive(obj)Determines whether object requires recursive representation.
pprint.isrecursive(1) -- false pprint.isrecursive({1, 2, 3}) -- true
-
pprint.isreadable(obj)Determines whether the formatted representation of object is "readable" that can be used to reconstruct the object's value via
load().pprint.isreadable(1) -- true pprint.isreadable({1, 2, 3}) -- true pprint.isreadable({ 'tom', 28, say = function () print('hello') end }) -- false
The pprint library define a class:
pprint.PrettyPrinter(args)
-- Create a `PrettyPrinter` instance.
local pp = pprint.PrettyPrinter({...})The args support some arguments:
args.indent: integer, Number of spaces to indent for each level of nesting.args.width: integer, Attempted maximum number of columns in the output.args.depth: integer, Depth limit, exceeding the limit will be folded.args:compact: boolean, If true, several items will be combined in one line.args:sort_tables: boolean, If true, sort the table by key.args.scientific_notation: boolean, If true, will display number with scientific notation.args.color: boolean, If true, will format with color escape.
The function provided:
PrettyPrinter:pprint(obj)PrettyPrinter:pformat(obj)PrettyPrinter:isrecursive(obj)PrettyPrinter:isreadable(obj)
- Pure lua implementation, no external lib dependencies.
- Support color output.
- Work with lua >=5.2
