2012-05-14 38 views
0

在lua中顯示數組時,它總是以1開頭,所以如果我使用select * from ...作爲table.id的引用,則在我的sql查詢中使用它。我現在的問題是如果table.id的sql查詢不會以1開頭,或者它會像[3,5,6, ...]那樣?lua中的數組索引

我的代碼是這樣的,

local data = {} 

for row in db:nrows("SELECT song.id as id, song.title as song, artist.name as artist, genre.name as genre, album.title as album FROM song, artist, genre, album WHERE song.artist_id = artist.id AND song.genre_id = genre.id AND song.album_id = album.id AND song.duration = 120.00") do 
         data[row.id] = {} 
         data[row.id].song = row.song 
         data[row.id].artist = row.artist 
         data[row.id].genre = row.genre 
         data[row.id].album = row.album 
end 

這樣的row.id輸出是[3,5,6,..]因爲我使用的row.id作爲數組data的索引。

我的問題是我應該怎麼做或使用,以便陣列data的索引將變成這樣,[1,2,3,....]?

回答

2

你可以只使用一個索引變量:

local data = {} 
local next = 1 

for row in db:nrows("SELECT song.id as id, song.title as song, artist.name as artist, genre.name as genre, album.title as album FROM song, artist, genre, album WHERE song.artist_id = artist.id AND song.genre_id = genre.id AND song.album_id = album.id AND song.duration = 120.00") do 
    data[next] = row 
    next = next + 1 
end