code / lua-differ

Lines184 Lua131 Markdown53

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

1 make_diff = require "diff"
2 s1 = [[hello
3 ...
4 to the
5 world]]
6 s2 = [[hello
7 ...
8 *at* the
9 world]]
10 diff = make_diff(s1, s2)

returns the table:

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

and running:

1 diff:print{color=false}

produces the output:

1 hello
2 ...
3 - to the
4 + *at* the
5 world

You can also diff tables:

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

returns:

1 {{old={1}, old_first=1, old_last=1, new={99}, new_first=1, new_last=1},
2 {old={2}, old_first=2, old_last=2, new={2}, new_first=2, new_last=2},
3 {old={3}, old_first=3, old_last=3, new={}, new_first=3, new_last=2},
4 {old={4, 5}, old_first=4, old_last=5, new={4, 5}, new_first=3, new_last=4},
5 {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)