As a summary of the basic part of Lua, This article demonstrates two small programs to demonstrate different features of Lua. The first example shows how Lua is used as a descriptive language. The first example is the implementation of a Markov Chain Algorithm.
PS: I personally think this chapter in the book is a bit confusing. I feel that the two examples have not been used in any summary, but I feel a little confused.
1. Data Description
A database is retained on Lua's website, storing some sample code for projects that use Lua in the world. We use a struct to represent every entry in the database, as shown below:
entry{ title = "Tecgraf", org = "Computer Graphics Technology Group, PUC-Rio", url = "http://www.tecgraf.puc-rio.br/", contact = "Waldemar Celes", description = [[ Tecgraf is the result of a partnership between PUC-Rio, the Pontifical Catholic University of Rio de Janeiro, and <a HREF="http://www.petrobras.com.br/">PETROBRAS</a>, the Brazilian Oil Company. Tecgraf is Lua's birthplace, and the language has been used there since 1993. Currently, more than thirty programmers in Tecgraf use Lua regularly; they have written more than two hundred thousand lines of code, distributed among dozens of final products.]]}
A data file containing a series of such entries is actually a Lua program, which uses table as the parameterEntryFor a series of calls.
We need to write a program to display the data in HTML format, and the data will become webpage http://www.lua.org/uses.html. Because there are many projects, the final page first lists the themes of all projects, and then shows the details of each project. As shown below, it is a typical output of the program:
To read data, the program simply definesEntryAnd then useDofileRun the data file. Note: We must traverse all entries twice. The first is to get the topic list and the second is to get the project description. One way is to collect all entries into an array. However, there is another attractive method: run the data file twice and use differentEntryDefinition. The second method is used below.
First, we define a function for formatting and writing:
function fwrite (fmt, ...) return io.write(string.format(fmt, ...))end
FunctionWriteheaderWrite the page header as follows:
function writeheader() io.write([[
EntryThe first definition of, write each project topic to the list as an entry, parameterOIs the table describing the project:
function entry1 (o) count = count + 1 local title = o.title or '(no title)' fwrite('<li><a href="#%d">%s</a>\n', count, title)end
IfO. TitleIsNil(That is, this field is not provided). The function uses a fixed "(No title )".
EntryThe second definition is as follows: write all the useful data of a project. It is a little complicated because all options are optional. (Double quotation marks are used in HTML. To avoid conflicts with HTML, we use single quotation marks in the program ).
function entry2 (o) count = count + 1 fwrite('
Last functionWritetail, Write the page tail.
function writetail () fwrite('</body>
The main program is as follows. The program opens the page, loads data files, and usesEntryTo create a topic list, reset the counter, and then useEntryTo run the data file, and finally close the page.
local inputfile = 'db.lua'writeheader()count = 0f = loadfile(inputfile) -- loads data fileentry = entry1 -- defines 'entry'fwrite('<ul>\n')f() -- runs data filefwrite('</ul>\n')count = 0entry = entry2 -- redefines 'entry'f() -- runs data file againwritetail()
The above code is summarized as follows:
function fwrite (fmt, ...) return io.write(string.format(fmt, ...))endfunction writeheader() io.write([[
The content of the DB. Lua file is as follows:
entry{ title = "Tecgraf", org = "Computer Graphics Technology Group, PUC-Rio", url = "http://www.tecgraf.puc-rio.br/", contact = "Waldemar Celes", description = [[ TeCGraf is the result of a partnership between PUC-Rio, the Pontifical Catholic University of Rio de Janeiro, and <A HREF="http://www.petrobras.com.br/">PETROBRAS</A>, the Brazilian Oil Company. TeCGraf is Lua's birthplace, and the language has been used there since 1993. Currently, more than thirty programmers in TeCGraf use Lua regularly; they have written more than two hundred thousand lines of code, distributed among dozens of final products.]] } entry{ title = "Tecgraf_02", org = "Computer Graphics Technology Group, PUC-Rio, the 2nd entry", url = "http://www.tecgraf.puc-rio.br/, the 2nd entry", contact = "Waldemar Celes 02", description = [[ This is the 2nd entry, TeCGraf is the result of a partnership between PUC-Rio, the Pontifical Catholic University of Rio de Janeiro, and <A HREF="http://www.petrobras.com.br/">PETROBRAS</A>, the Brazilian Oil Company. TeCGraf is Lua's birthplace, and the language has been used there since 1993. Currently, more than thirty programmers in TeCGraf use Lua regularly; they have written more than two hundred thousand lines of code, distributed among dozens of final products.]] }
The running result is as follows:
2. Markov Chain Algorithm
The 2nd example is the implementation of the Markov Chain Algorithm. This program generates random text based on the first n words in the text. Here we assume that N is 2.
In the first part of the program, read the basic text and create a table. Each two words is a prefix, which stores the words (possibly multiple) after the prefix in the basic text into the table. After the table is created, the program uses this table to randomly generate text. The probability of words with each prefix is roughly the same as that in basic text. In this way, we can get a fairly random text.
We will link the two words with a space "" and encode them as the prefix:
function prefix (w1, w2) return w1 .. " " .. w2end
We use the string noword ("\ n") to initialize the prefix word and mark the end of the text. For example:
the more we try the more we do
The generated table will be:
{["\ N"] = {"the"}, ["\ n the"] = {"more "}, ["The more"] = {"we", "we"}, -- there are two places: "The more we" ["more we"] = {"try ", "Do"}, -- two places "more we try", "more we do" ["We try"] = {""}, ["try the"] = {"more"}, ["we do"] = {"\ n "},}
The program saves its table to the variable statetab. We use the following function to insert a new word into the table prefix list.
function insert (index, value) local list = statetab[index] if list == nil then statetab[index] = {value} else list[#list + 1] = value endend
It first checks whether the prefix has a list. If yes, use this new value to create a new list. Otherwise, insert the new value to the end of the existing list.
To create the table statetab, we save two variables, W1 and W2, and save the last two words read. Every time we read a new word, we add it to the list associated with the w1-w2, and then update W1 and W2.
After this table is created, the program starts to use maxgen words to generate text. First, it reinitializes W1 and W2. Then, for each prefix, it randomly selects one from the Legal list of the next word, prints the word, and then updates W1 and W2. below is the full version of the program.
-- Auxiliary definitions for the Markov programfunction allwords () local line = io.read() -- current line local pos = 1 -- current position in the line return function () -- iterator function while line do -- repeat while there are lines local s, e = string.find(line, "%w+", pos) if s then -- found a word? pos = e + 1 -- update next position return string.sub(line, s, e) -- return the word else line = io.read() -- word not found; try next line pos = 1 -- restart from first position end end return nil -- no more lines: end of traversal endendfunction prefix (w1, w2) return w1 .. " " .. w2endlocal statetab = {}function insert (index, value) local list = statetab[index] if list == nil then statetab[index] = {value} else list[#list + 1] = value endend-- The Markov programlocal N = 2local MAXGEN = 10000local NOWORD = "\n"-- build tablelocal w1, w2 = NOWORD, NOWORDfor w in allwords() do insert(prefix(w1, w2), w) w1 = w2; w2 = w;endinsert(prefix(w1, w2), NOWORD)-- generate textw1 = NOWORD; w2 = NOWORD -- reinitializefor i=1, MAXGEN do local list = statetab[prefix(w1, w2)] -- choose a random item from list local r = math.random(#list) local nextword = list[r] if nextword == NOWORD then return end io.write(nextword, " ") w1 = w2; w2 = nextwordend
The running result is as follows:
The level is limited. If a friend finds an error, please leave a message.