Lua provides helper functions to operate tables. For example, the insert and remove elements in the list can be sort for the array elements, or all strings in the concatenate array. The following describes these methods in detail.
Insert and removeTable. Insert inserts an element into a specified position, for example:
T = {1, 2, 3} table. the insert (T, 1, 4} t result will be the second parameter of {4, 1, 2, 3} insert, which can be omitted, in this way, it is inserted to the end of the array, so that other elements do not have to be moved. Similarly, table. remove is to remove (and return) an element from the array, table. remove (T, 1) removes the element whose subscript is 1 in T. If the position is not specified, the last element is removed.
Through the insert and remove methods, stacks, queues, and double queues can be directly implemented. the push operation is equivalent to the table. insert (t, x), and the pop operation is equivalent to table. remove (T). For example, define a stack:
Stack ={} function Stack: Push (x) Table. insert (self, x) End
Function Stack: Pop () Table. Remove (Self) End
SortAnother useful function is sort, which sorts arrays. If no sort function is provided, the default operation is <. The common mistake is to try to sort table keys. In a table, all the keys constitute a set, and there is no sequence in the walls. If you want to sort them, first copy them to an array and then perform sort. If we want to iterate a table in the order of sorted keys, we can write this iterator: function pairsbykeys (T, F) local a ={} for K in pairs (t) Do A [# A + 1] = K end table. sort (A, F) Local I = 0 return function () I = I + 1 return a [I], t [A [I] endend
ConcatenationFor a given table, if all elements are strings or numbers, table [I] is returned. SEP .. table [I + 1] · Sep .. table [J]. The Delimiter is a null string by default, I is 1 by default, and J is the table length by default. If I> J, a null string is returned. For example:
Spring = {"spring forest is becoming more prosperous", "spring water is born", "spring breeze is better than you "}
Print (table. Concat (Spring ,","))
(End)
Commonly used functions in the Lua table Library