LUA Data Structures

Source: Internet
Author: User

Table in Lua is not a simple data structure, it can be used as a basis for other data structures. Array arrays, record records, linear table lists, queue queues, and set set are all represented by table in Lua.

Array

arrays are simply implemented in LUA by using an integer subscript to access the elements in the table . And the array does not have to specify the size beforehand, the size can grow dynamically as needed.

A = {}for i = 1,100 do    a[i] = 0endprint ("The length of an array ' a ' is"). #a) squares = {1, 4, 9, 25}print ("The length of the array ' a ' is"). #squares)
The following table that is accustomed to arrays in Lua starts from 1, the standard library of LUA is consistent with this habit, so if your array subscript is starting from 1 You can use the standard library function directly, otherwise you won't be able to use it directly.Linked listIt is easy to implement a linked list with tables in Lua, where each node is a table, the pointer is a field (field) of the table, and points to another node (table). For example, to implement a basic list of only two domains: values and pointers , code such as: root node: list = nil; Insert a node with a value of V at the beginning of the list: list = {next = list, value = v}
Local List = Nilfor i = 1, ten do    list = {next = list, value = i}endlocal L = listwhile l do     print (l.value)    l = L.nextend

other types of linked lists, like doubly linked lists and circular lists, are also easy to implement . These data structures are then needed in LUA in rare cases, as there is usually an easier way to replace a linked list. For example, we can use a very large array to represent the stack, where a field n points to the top of the stack.

queues and bidirectional queues Although it is possible to implement queues using the insert and remove operations provided by the table Library of LUA, the implementation of a queue in this way is inefficient when it comes to large data volumes, using two index subscripts, one representing the first element and the other representing the last element.

below, we can do this in the constant time

local List = {}  function List.new () return {first = 0, last = -1}endfunction list.pushleft (List, value) Local first = List.first- 1 List.first = First List[first] = valueendfunction list.pushright (list, value) Local last = List.last + 1 L Ist.last = Last List[last] = valueendfunction list.popleft (list) Local first = List.first if first > List.las T then error (' list is empty ') end local value = List[first] list[first] = nil--To allow garbage collection L  Ist.first = first + 1 return valueendfunction list.popright (List) Local last = List.last if List.first > Last Then error (' list is empty ') end local value = List[last] list[last] = nil--To allow garbage collection lis T.last = last-1 return valueend 
In the strict sense of the queue, we can only invoke Pushright and Popleft, so since the first and last index values have increased, fortunately we use the LUA table implementation, you can access the elements of the array, by using subscripts from 1 to 20, can also be 16,777,216 to 16,777,236.CollectionSuppose you want to list all the identifiers that appear in a source code, in a way, you need to filter out the reserved words of those languages themselves. Some C programmers like to use a string array to represent, all the reserved words in the array, for each identifier into the array to see if it is a reserved word, and sometimes in order to improve query efficiency, the use of binary search or hash algorithm for the array storage.
LUA indicates that this collection has a simple and efficient way to store all the elements in the collection as subscripts in a table, without having to look up the table, just to test to see if the corresponding subscript element value for the given element is nil. Like what:
reserved = {["while"] = True,    ["end"] = true,["function"] = true, ["local"] = True,}for W in allwords () do    if Rese RVED[W]    then – ' W ' is a reserved word    endend--You can also construct the collection more clearly using helper functions: function Set (list)    local set = {} for    _ , l in Ipairs (list) does set[l] = True End    return setendreserved = set{"while", "End", "function", "Local",}
Description: The element of the collection is the key of the table, not the value. The original collection is: {"While", "End", "function", "Local",}

In Lua we can consider a package (bag) as a multiset, unlike a normal set, where the same element in the container allows key to appear multiple times in the container . The following code simulates implementing the data structure by adding a counter to the elements in the table, such as:

function insert (bag, Element)    bag[element] = (Bag[element] or 0) + 1endfunction Remove (bag, Element)    Local count = Bag[element]    Bag[element] = (count and Count > 1) and Count-1 or Nilend
String bufferingIf you want to concatenate multiple strings into a large string in Lua, you can do so in the following ways, such as:
Local buff = "" For line in Io.lines () do    buff = buff. Line.. "\ n" End
The above code does work properly, but when the number of rows is high, this method will result in a large amount of memory reallocation and data copying between the memory, resulting in considerable performance overhead . In fact, in many programming languages, string is immutable, such as Java, so if you concatenate large strings multiple times in this way, you will cause the same performance problem. To solve this problem, the StringBuilder class is available in Java, and LUA can use the table's Concat method to solve the problem, as shown in the following code:
Local T = {}for line in Io.lines () does    t[#t + 1] = line: "\ n" endlocal s = Table.concat (t)--concat method can accept two parameters, so the above can also be changed to: local t = {}for line in Io.lines () does    t[#t + 1] = line endlocal s = table.concat (t, "\ n")


LUA Data Structures

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.