Lua Arrays - Lua (programming language)

What are Arrays in Lua?

Arrays in Lua are structured arrangement of objects. This can be a one dimensional array consisting of a collection of rows or a multi-dimensional array consisting of multiple rows and columns.

In Lua, arrays are implemented by using indexing tables with integers. Size of an array will not be fixed and it will grow depending on the requirements related to memory constraints.

One-Dimensional Array

One-dimensional array is represented by using a simple table structure and is initialized and read using a simple for loop. Below is an example.

When you run the above code, below output will be displayed.

In the above code, if you are trying to access an element in an index which is not present in the array, it will return nil. In Lua, indexing will usually start at index 1. But you can also create objects at index 0 and below 0. Array using negative indices is shown below where an array is initialized using a for loop.

When you run the above code, below output will be displayed.

Multi-Dimensional Array

Multi-dimensional arrays will be implemented in two ways.

  • Array of arrays
  • Single dimensional array by manipulating indices

Example for multidimensional array of 3. 3 is shown below using array of arrays.

When you run the above code, below output will be displayed.

Example for multidimensional array is shown below using manipulating indices.

When you run the above code, below output will be displayed.

In the above example, data is stored based upon the indices. Elements can also be placed in a sparse way and it is the way Lua implementation of a matrix works. As it doesn’t store nil values in Lua, lots of memory can be saved without any special technique in Lua when compared to other special techniques used in other programming languages.

All rights reserved © 2020 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

Lua (programming language) Topics