Consider a data source with the following data. This example creates a glossary of all the words in the ‘Glossary’ field, showing the pages they appear on. The words are sorted alphabetically and the pages are numerical within each word.
The resulting output looks something like:
big – p 13,14,
bill – p 13,
black – p 14,
bone – p 13,
comb – p 16,
feathers – p 13,16,
feline – p 14,16,17,18,
horns – p 14,
mane – p 16,
neck – p 14,
spots – p 14,
stripes – p 17,
tail – p 14,18,
trunk – p 13,
whiskers – p 18,
wool – p 16,
Here’s the code required to produce the output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 | -- split 'str' into parts and add to 'table' local function split(table, str, sep) local regex = ("([^%s]+)"):format(sep) for each in str:gmatch(regex) do table[each] = 1; end end -- check if the glossary table contains a given word local function contains(glossary, word) local keys = {}; split(keys, glossary, ",") return keys[word] ~= nil; end; -- return table contents ordered by the table key function pairsByKeys (t, f) local a = {} for n in pairs(t) do table.insert(a, n) end table.sort(a, f) local i = 0 -- iterator variable local iter = function () -- iterator function i = i + 1 if a[i] == nil then return nil else return a[i], t[a[i] ] end end return iter end; -- Execution starts here -- get a recordset for our data source mydatasource = DATASOURCE.get('Glossary.xlsx'); recordset = mydatasource:getrecordset(); -- populate a table 'xxx' with a unique words from the 'Glossary' field -- a single field may contain multiple comma separated words -- tables in lua are key,value pairs. The word is made unique by putting -- the word in the key. Value is assigned a arbitrary value of '1' xxx = {}; for record = 1,recordset:size() do myRecord = recordset:getrecord(record); glossary = myRecord:field('Glossary'):content(); split(xxx, glossary, ",") end -- iterate through the words in alphabetical order for word,line in pairsByKeys(xxx) do TEXT.insert(word); TEXT.insert(' - p '); local pages = {}; -- construct 'pages' a table of page numbers this word appears on for record =1,recordset:size() do myRecord = recordset:getrecord(record); PageNo = myRecord:field('PageNo'):content(); glossary = myRecord:field('Glossary'):content(); if (contains(glossary, word)) then; pages[tonumber(PageNo)] = 1; end; end; -- get the page numbers in numerical order for key,value in pairsByKeys(pages) do TEXT.insert(key); TEXT.insert(','); end; TEXT.insert('^n'); end; |