WordList¶
A WordList object is a list of unique words that can be used to test whether or not some word exists within that list.
It is most useful for large and/or long-lived lists. If you only want to test against a handful of words, it will likely be more efficient to use a table keyed by word instead.
WordLists have following functions:
WordList()
WordList( filename )¶
Creates a new WordList object. You can either create an empty WordList (which you can populate later), or create a WordList from a file on disk. If you create one from a file on disk, each line of the file should contain a single word and nothing else.
Example¶
1 2 3 | local cta = require 'cta'
local empty = cta.WordList()
local fromFile = cta.WordList( 'my-custom-wordlist.txt' )
|
WordList:addFromFile( filename )¶
Adds each line from the file specified in filename
as a single word of the
WordList.
Example¶
1 2 3 4 5 6 | local cta = require 'cta'
local wordList = cta.WordList( 'wordlist1.txt' )
-- wordList will now contain all the unique words from the
-- files 'wordlist1.txt' and 'wordlist2.txt'
wordList:addFromFile( 'wordlist2.txt' )
|
WordList:addFromWordList( otherList )¶
Adds all the words from otherList
to the current list.
Example¶
1 2 3 4 5 6 | local cta = require 'cta'
local wordList1 = cta.WordList( 'wordlist.txt' )
local wordList2 = cta.WordList()
-- wordList2 will now contain the same words as wordList1
wordList2:addFromWordList( wordList1 )
|
WordList:addWord( word )¶
Adds a single word to the WordList.
Example¶
1 2 3 4 5 | local cta = require 'cta'
local wordList = cta.WordList()
-- wordList will now contain a single word '佟掌柜'.
wordList:addWord( '佟掌柜' )
|
Performance Note: If you are repeatedly creating a WordList with a small number of words (e.g. in a loop), you will likely have better performance using a table keyed by word, rather than a WordList.
WordList:contains( word )¶
Tests to see if a word exists within in the list and returns true
if so and
false
if not.
Example¶
1 2 3 4 5 6 7 8 | local cta = require 'cta'
local wordList = cta.WordList( 'wordlist1.txt' )
if wordList:contains( '双煞' ) then
print( 'Wordlist contains 双煞' )
else
print( 'Wordlist does not contain 双煞' )
end
|
WordList:words()¶
Returns an iterator that will iterate over all words in the WordList. Each element of the iteration will be a string.
The order of iteration will be different than the order the words were added to the list, but will be consistent across all iterations.
Example¶
1 2 3 4 5 6 | local cta = require 'cta'
local wordList = cta.WordList( 'wordlist.txt' )
for word in wordList:words() do
...
end
|
Operators¶
WordList objects also support the following Lua operators: +, - and #.