Stories

Detail Return Return

Lua一維數組與多維數組的使用示例 - Stories Detail

Lua語言中,數組和C還是有區別的,Lua的數組下標從1開始計數,而C語言的數組下標從0開始計數,我想這可能是設計Lua的人想要符合人的思維習慣而去這麼設計的。

數組,也就是按相同類型,在內存中順序排列的一個組合,這點跟C基本沒多大的差別。

接下來看1個例子:

test7.lua

--一維數組,數組的成員是字符串
array = {"Lua","Study"};
for i = 1 , 2 do
  print(array[i]);
end
--一維數組,數組的成員是整型數據
array1 = {1,2,3,4,5,6,7,8,9,10};
for i = 1 , 10 do
  print(i);
end
--循環執行次數
--第一次 i = 1 , j = 1 , array[i][j] = i * j = 1 * 1 = 1
--第二次 i = 1 , j = 2 , array[i][j] = i * j = 1 * 2 = 2
--第三次 i = 2 , j = 1 , array[i][j] = i * j = 2 * 1 = 2
--第四次 i = 2 , j = 2 , array[i][j] = i * j = 2 * 2 = 4
--初始化一個2 * 2 的多維數組
array = {}; 
for i = 1 , 2 do
  array[i] = {} ;
  for j = 1 , 2 do
   array[i][j] = i * j ; 
  end
end 
--打印這個數組的值
for i = 1 , 2 do
  for j = 1 , 2 do
  print(array[i][j]);
end 
end

解釋運行: lua test7.lua

運行結果:

Lua
Study
1
2
3
4
5
6
7
8
9
10
1
2
2
4

Add a new Comments

Some HTML is okay.