Lua用table模拟二维数组
1 local array = {}; 2 local row1 = {1, 3, 5, 7, 9} 3 local row2 = {2, 4, 6, 8, 10} 4 local row3 = {"I", "love", "lua"} 5 array[1] = row1; 6 array[2] = row2; 7 array[3] = row3 8 print("length = ", #array); 9 for i = 1, #array do 10 for j = 1, #array[i] do 11 print(array[i][j]) 12 end 13 end
1 function Create2DArray(row, col) 2 local array2D = {} 3 for i = 1, row do 4 array2D[i] = {} 5 for j = 1, col do 6 array2D[i][j] = 0 7 end 8 end 9 return array2D 10 end
1 function Print2DArray(array) 2 local str = "" 3 for i = 1, #array do 4 for j = 1, #array[i] do 5 str = table.concat(array[i], " ") 6 end 7 print(str) 8 end 9 end