YouTip LogoYouTip

Lua Tables

A table is a data structure in Lua that helps us create different data types, such as arrays, dictionaries, etc. Lua tables use associative arrays, where you can use a value of any type as the index of the array, except for `nil`. Lua tables are not of fixed size; you can expand them as needed. Lua also uses tables to implement modules, packages, and objects. For example, `string.format` means using "format" to index the `string` table. * * * ## Table Construction A constructor is an expression that creates and initializes a table. Tables are a powerful feature unique to Lua. The simplest constructor is `{}`, which creates an empty table. You can initialize an array directly: ```lua -- Initialize table mytable = {} -- Assign values mytable = "Lua" -- Remove reference mytable = nil -- Lua garbage collection will free the memory When we set elements for table `a` and then assign `a` to `b`, both `a` and `b` point to the same memory. If `a` is set to `nil`, `b` can still access the table's elements. If no variable points to `a`, Lua's garbage collection mechanism will clean up the corresponding memory. The following example demonstrates the described situation: ## Example ```lua -- Simple table mytable = {} print("mytable type is ", type(mytable)) mytable = "Lua" mytable = "before modification" print("mytable element at index 1 is ", mytable) print("mytable element at index wow is ", mytable) -- alternatetable and mytable refer to the same table alternatetable = mytable print("alternatetable element at index 1 is ", alternatetable) print("alternatetable element at index wow is ", alternatetable) alternatetable = "after modification" print("mytable element at index wow is ", mytable) -- Release variable alternatetable = nil print("alternatetable is ", alternatetable) -- mytable can still be accessed print("mytable element at index wow is ", mytable) mytable = nil print("mytable is ", mytable) The output of the above code is: mytable type is table mytable element at index 1 is Lua mytable element at index wow is before modification alternatetable element at index 1 is Lua alternatetable element at index wow is before modification mytable element at index wow is after modification alternatetable is nil mytable element at index wow is after modification mytable is nil * * * ## Table Operations The following lists common methods for table operations: | No. | Method & Purpose | | --- | --- | | 1 | **table.concat (table [, sep [, start [, end]]]):** `concat` is short for concatenate. The `table.concat()` function lists all elements of the specified table's array part from the `start` position to the `end` position, with elements separated by the specified separator (`sep`). | | 2 | **table.insert (table, [pos,] value):** Inserts an element with value `value` at the specified position (`pos`) in the table's array part. The `pos` parameter is optional and defaults to the end of the array part. | | 3 | **table.maxn (table):** Returns the largest key among all positive numeric keys in the specified table. If no positive numeric key exists, it returns 0. (**This method has been removed since Lua 5.2; this tutorial uses a custom function implementation.**) | | 4 | **table.remove (table [, pos]):** Returns the element located at position `pos` in the table's array part. Subsequent elements are shifted forward. The `pos` parameter is optional and defaults to the length of the table, i.e., deleting from the last element. | | 5 | **table.sort (table [, comp]):** Sorts the given table in ascending order. | Next, let's look at examples of these methods. ### Table Concatenation We can use `concat()` to output a string formed by concatenating elements of a list: ## Example ```lua fruits = {"banana", "orange", "apple"} -- Return the concatenated string of the table print("Concatenated string ", table.concat(fruits)) -- Specify the concatenation character print("Concatenated string ", table.concat(fruits, ", ")) -- Specify indices to concatenate the table print("Concatenated string ", table.concat(fruits, ", ", 2, 3)) The output of the above code is: Concatenated string bananaorangeapple Concatenated string banana, orange, apple Concatenated string orange, apple ### Insertion and Removal The following example demonstrates table insertion and removal operations: ## Example ```lua fruits = {"banana", "orange", "apple"} -- Insert at the end table.insert(fruits, "mango") print("Element at index 4 is ", fruits) -- Insert at index 2 table.insert(fruits, 2, "grapes") print("Element at index 2 is ", fruits) print("Last element is ", fruits) table.remove(fruits) print("Last element after removal is ", fruits) The output of the above code is: Element at index 4 is mango Element at index 2 is grapes Last element is mango Last element after removal is nil ### Table Sorting The following example demonstrates the use of the `sort()` method for sorting a table: ## Example ```lua fruits = {"banana", "orange", "apple", "grapes"} print("Before sorting") for k, v in ipairs(fruits) do print(k, v) end table.sort(fruits) print("After sorting") for k, v in ipairs(fruits) do print(k, v) end The output of the above code is: Before sorting 1 banana 2 orange 3 apple 4 grapes After sorting 1 apple 2 banana 3 grapes 4 orange ### Table Maximum Value `table.maxn` has been removed since Lua 5.2. We define a `table_maxn` method to implement it. The following example demonstrates how to get the maximum value in a table: ## Example ```lua function table_maxn(t) local mn = nil; for k, v in pairs(t) do if (mn == nil) then mn = v end if mn **Note:** > > When we get the length of a table, whether using `#` or `table.getn`, it will stop counting at the point where the index is interrupted, leading to an inability to correctly obtain the length of the table. > > You can use the following method as a substitute: > > ```lua > function table_leng(t) > local leng = 0 > for k, v in pairs(t) do > leng = leng + 1 > end > return leng; > end > ```
← Lua Data TypesLua Environment β†’