Lua Learning (one)--lua arrays

Source: Internet
Author: User

An array is a collection of elements of the same data type arranged in a certain order, which can be one-dimensional and multidimensional arrays.
The index key values of the Lua array can be represented by integers, and the size of the array is not fixed. one-dimensional arrays

A one-dimensional array is the simplest array, and its logical structure is a linear table. A one-dimensional array can be used in the for loop to the elements in a group, as follows:

Array = {"Lua", "Tutorial"} for

i= 0, 2 does
   print (Array[i])
end

The results are:

Nil
Lua
Tutorial

* * As you can see, we could use an integer index to access the array element and return nil If we know the index has no value.
The Lua index value starts with 1, but you can also specify 0 to start. **

In addition we can also index values in negative numbers:

Array = {}

for i=-2, 2 does
   array[i] = i *2 end for

i = -2,2 does
   print (array[i))
end

Output results:

-4
-2
0
2
4
Multidimensional Arrays

A multidimensional array is an array of index keys that contain an array or a one-dimensional array.
The following is an array multidimensional array of three rows and three columns:

--Initialize array
= {} for
i=1,3 does
   array[i] = {} for
      j=1,3 does
         array[i][j] = I*j end

--Visit Ask the array for i=1,3 do to
   j=1,3 do
      print (Array[i][j]
   )
end

The results are as follows:

1
2
3
2
4
6 3 6 9

Three row three array multidimensional arrays of different index keys:

--Initialize array
= {}
maxRows = 3
maxcolumns = 3 for row=1,maxrows does for
   col=1,maxcolumns do
  
   array[row*maxcolumns +col] = Row*col
   End

--access array
for row=1,maxrows does
   for col=1, MaxColumns do
      print (Array[row*maxcolumns +col])
   End

  

Output results:

123246369

As you can see, in the above example, the array sets the specified index value, which avoids the nil value and helps conserve memory space.

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.