code / lua-differ

Lines184 Lua131 Markdown53
(67 lines)

LuaDiffer: A simple lua diff library

This is a simple lua module that performs a diff on two strings and returns a table of string chunks, or a diff of two lists and returns a list of list subsets.

Example

make_diff = require "diff"
s1 = [[hello
...
to the
world]]
s2 = [[hello
...
*at* the
world]]
diff = make_diff(s1, s2)

returns the table:

{
  {old="hello\n...\n", old_first=1, old_last=2,
   new="hello\n...\n", new_first=1, new_last=2},
  {old="to the\n", old_first=3, old_last=3,
   new="*at* the\n", new_first=3, new_last=3},
  {old="world", old_first=4, old_last=4,
   new="world", new_first=4, new_last=4},
}

and running:

diff:print{color=false}

produces the output:

  hello
  ...
- to the
+ *at* the
  world

You can also diff tables:

diff({1,2,3,4,5},{99,2,4,5,6})

returns:

{{old={1},    old_first=1, old_last=1, new={99},   new_first=1, new_last=1},
 {old={2},    old_first=2, old_last=2, new={2},    new_first=2, new_last=2},
 {old={3},    old_first=3, old_last=3, new={},     new_first=3, new_last=2},
 {old={4, 5}, old_first=4, old_last=5, new={4, 5}, new_first=3, new_last=4},
 {old={},     old_first=6, old_last=5, new={6},    new_first=5, new_last=5}}

(when diffing tables, it is guaranteed that for matching chunks, .old and .new refer to the same table, so chunk.old == chunk.new will succeed)

1 # LuaDiffer: A simple lua diff library
3 This is a simple lua module that performs a diff on two strings and returns a table of
4 string chunks, or a diff of two lists and returns a list of list subsets.
6 ## Example
8 ```lua
9 make_diff = require "diff"
10 s1 = [[hello
11 ...
12 to the
13 world]]
14 s2 = [[hello
15 ...
16 *at* the
17 world]]
18 diff = make_diff(s1, s2)
19 ```
21 returns the table:
23 ```lua
25 {old="hello\n...\n", old_first=1, old_last=2,
26 new="hello\n...\n", new_first=1, new_last=2},
27 {old="to the\n", old_first=3, old_last=3,
28 new="*at* the\n", new_first=3, new_last=3},
29 {old="world", old_first=4, old_last=4,
30 new="world", new_first=4, new_last=4},
32 ```
34 and running:
36 ```lua
37 diff:print{color=false}
38 ```
40 produces the output:
42 ```
43 hello
44 ...
45 - to the
46 + *at* the
47 world
48 ```
50 You can also diff tables:
52 ```lua
53 diff({1,2,3,4,5},{99,2,4,5,6})
54 ```
56 returns:
58 ```lua
59 {{old={1}, old_first=1, old_last=1, new={99}, new_first=1, new_last=1},
60 {old={2}, old_first=2, old_last=2, new={2}, new_first=2, new_last=2},
61 {old={3}, old_first=3, old_last=3, new={}, new_first=3, new_last=2},
62 {old={4, 5}, old_first=4, old_last=5, new={4, 5}, new_first=3, new_last=4},
63 {old={}, old_first=6, old_last=5, new={6}, new_first=5, new_last=5}}
64 ```
66 (when diffing tables, it is guaranteed that for matching chunks, .old and .new refer to
67 the same table, so `chunk.old == chunk.new` will succeed)