Table in Lua is not a simple data structure, it can be used as a basis for other data structures. Data structures provided in other languages, such as arrays, records, linear tables, queues, collections, etc., can be represented in LUA by table. and using LUA to implement these data structures is highly efficient.
The array does not have a fixed size in Lua and can increase the length as needed. When an array is initialized, it is also indirectly defined by its size. Second, matrix and multidimensional arrays in Lua, there are two ways to represent matrices, one is to use an array of arrays, which is an array of elements. Another way to do this is to merge the indexes, and there are two ways to merge the indexes, adding an index delimiter and calculating how the values are combined. A table stores all the values in a merged index. 1, calculate the value, (idx-1) *m + Idy The way to calculate the value of each index 2, add delimiter, N. S.. M implementing a unique key by using a string connection the list is convenient to implement in Lua because the table in Lua is a dynamic entity. Each linked table node is represented by a table, and the node contains two values, next and value, and note that the next of the tail node is nil. Four, two-way queue the implementation of Lua Squadron is a relatively simple implementation method is to use the table library function insert and remove. These two functions can insert and delete elements anywhere in an array, and move subsequent elements as required by the operation. But for larger structures, the overhead of moving is great. A more efficient implementation is to use two indexes, one for each of the two elements, and two-way queues:
--implementation of two-way queueDoublequeue= {}functiondoublequeue.new ()LocalQueue = {first =0, last =-1 } functionQueue.pushfirst (Queue,value)LocalFirst = Queue.first-1Queue.first=First queue[first]=valueEnd functionQueue.popfirst (Queue)LocalFirst =Queue.firstifFirst > Queue.last Then Error("queue is empty!")End LocalValue =Queue[first] Queue[first]=NilQueue.first= First +1 returnvalueEnd functionqueue.pushlast (Queue,value)LocalLast = Queue.last +1Queue.last=Last Queue[last]=valueEnd functionqueue.poplast (Queue)LocalLast =Queue.lastifLast < Queue.first Then Error("queue is empty!")End LocalValue =Queue[last] Queue[last]=NilQueue.last= Last-1 returnvalueEnd functionQueue.len (Queue)returnQueue.last-queue.first +1 End returnQueueEnd
Lua Learning Notes (10) Data structure