【问题标题】:array indexing in lualua中的数组索引
【发布时间】:2012-05-21 13:45:44
【问题描述】:

在 lua 中显示数组时,它总是从 1 开始,所以如果我使用 select * from ... 作为 table.id 的引用,我会在我的 sql 查询中使用它。我现在的问题是如果table.id的sql查询不是以1开头,或者会像[3,5,6, ...]一样?

我的代码是这样的,

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,....]?

【问题讨论】:

    标签: arrays loops lua coronasdk


    【解决方案1】:

    你可以只使用一个索引变量:

    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
    

    【讨论】:

      猜你喜欢
      • 2017-03-13
      • 2018-05-20
      • 2014-02-09
      • 1970-01-01
      • 2020-12-27
      • 2016-09-23
      • 2012-05-19
      • 2018-02-23
      • 1970-01-01
      相关资源
      最近更新 更多