Programming in Lua 3 (26)

Source: Internet
Author: User
Tags tag name xml parser
Date: 2014.8.12part IV the C API
30. The custom types implemented in the previous section of managing resources are not concerned with resource management. The array implemented in the previous section is concerned with memory issues, which are managed by Lua. However, in many cases, it is not that simple. Some objects require not only memory space, but also resources such as window handles and file descriptions. Although these are memory overhead, these resources are managed by other components of the system. In this case, when an object is recycled, we also need an appropriate mechanism to reclaim these additional resources. In section 17.6, we introduce the finalizer provided by Lua, a mechanism consisting of the _ GC meta method. In order to manage resources normally in C and API, this chapter will expand two mechanisms from Lua. The first example is the implementation of a function traversing a directory; the second example is the binding of expat and a parser that opens XML resources.


30.1 a directory iteratorA similar dir function has been implemented before. The function returns a table containing all the files in the given directory. Here we need to implement each call to return an iterator representing an entry (equivalent to an element in the previous table), so that we can traverse a directory in the following way: E. g. for fname in Dir. open (". ") Do print (fname) end in C to traverse a directory, a dir data structure is required. In addition, the data structure dir instance needs to be created by opendir and must be released immediately when closedir is called. The implementation of the Dir function previously introduced is to store the Dir instance as a local variable, and then release the instance after obtaining the last file name. Then, the Dir instance cannot be stored as a local variable. Here, we consider that there will be multiple accesses to the instance. Not only that, but it cannot be done only when the last file name is obtained, because if the program exits the loop halfway, it will be released again. Therefore, we store the Dir instance address in the form of a userdataum, and then use the _ GC meta method to manage this userdataum to release this resource. We need to use three C functions to achieve our needs: 1. DIR is required. OPEN function, Lua is used to create an iterator. This function is used to open a dir structure, and then create a closure; 2, an iterator function in the form of upvalue; 3, __gc metamethod, used to release resources. Of course, an additional function is also required for parameter initialization. First, the Dir. OPEN function. Note that you must create userdatum before opening the directory, because memory errors may occur if the order is reversed. Based on the correct sequence, once the Dir structure is created, it is immediately linked to userdatum. Then, the _ GC meta method will take over the release of userdatum. Then, the dir_iter function obtains the Dir structure address from upvalue and calls readdir to read the next entry. Then, the dir_gc function represents the _ GC meta method. This method is used to disable the directory, but note that userdatum is created before the directory is opened. Therefore, no matter what the opendidr result is, userdatum is recycled. Finally, the luaopen_dir function is the function to open the library. All are implemented in the form of C functions.


30.2 an XML ParserHere we will introduce the simple implementation of Lua and expat binding, called lxp. Expat is an open-source xml1.0 parser written in C. The parser is implemented as SAX (The Simple API for XML ). Sax is an API-based event distributor, that is, the SAX Parser reads a line of XML documents, and then notifies the program to read the information through callback. For example, if we use expat to parse a string "<tag Cap =" 5 "> Hi </Tag>", three events are generated: when the sub-string "<tag cap-" 5> "is read, a start-element event is generated. When the sub-string" hi "is read, a text event is generated; an endelement event is generated when you read "</Tag>. Each event corresponds to a corresponding callback event in the program. Expat has many events. Here we mainly introduce the three events mentioned above. First, we will introduce the functions used to create and clear the expat Parser:
E.g. xml_parser xml_parsercreate (const char * encoding);/* Create */void xml_parserfree (xml_parser P);/* clear */
The parameter encoding in the first function is optional, and null is used here. After obtaining the parser, You need to register the callback handle:
Void xml_setelementhandler (xml_parser P, xml_startelementhandler start,/* Start event */end);/* end event */void Merge (xml_parser P, xml_characterdatahandler hndl ); /* Text event */
All callback handles accept user data as the first parameter. The start-element handle also accepts the Tag Name and tag attributes as its parameters.
typedef void (*XML_StartElementHandler) (void *uData,const char *name,const char **atts);
The End-element handle only accepts one additional parameter. The Tag Name:
typedef void(*XML_EndElementHandler)(void *uData,const char *name);
The text handle accepts text as its parameter plus the length of the text:
typedef void(*XML_CharacterDataHandler)(void *uData,const char *s,int len);
Pass the information to be parsed to the parser. Use the following function:
int XML_Parse(XML_Parser p,const char *s,int len,int isLast);
Expat accepts the documents to be parsed in blocks by calling xml_parse consecutively. The last islast parameter indicates whether the parsed block is the last one in the document. We use the actual length of each block as the parameter here, so we do not need to mark each block with a 0 Terminator. This function will return 0 in case of a parsing error. The final function is to set user data and pass it to each handle:
void XML_SetUserData(XML_Parser p ,void *uData);

Programming in Lua 3 (26)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.