for l循环如何用数组索引

时间:2012-05-11 08:32:20

标签: arrays for-loop lua corona

如果我有这个代码,怎么能把我的循环值放到数组中?

local data = {
 for row in db:nrows("SELECT song.id, song.title as title, artist.name as name FROM song, artist where song.artist_id = artist.id") do
    {
     song = row.title,
     artist = row.name
    }
  end
}

但我收到了这个错误:

unexpected symbol near 'for'

我只是想看起来像这样......

local data = {
 { 
   song = "HI",
   artist = "Tom"
 }
 {
   song = "Hello",
   artist = "mike"
 }
...
}

任何人都可以帮助我解决我的情况或提出一些建议吗? 提前谢谢

2 个答案:

答案 0 :(得分:3)

我认为你必须做这样的事情:

result = db:nrows("SELECT song.id, song.title as title, artist.name as name FROM song, artist where song.artist_id = artist.id")

data = {}
for i, row in ipairs(result) do
  data[i] = {}
  data[i].song = row.title
  data[i].artist = row.name
end

编辑:但问题是:为什么不在SQL查询中指定并按原样使用结果?即:

data = db:nrows("SELECT song.id, song.title as song, artist.name as artist FROM song, artist where song.artist_id = artist.id")

答案 1 :(得分:2)

查看了文档dbn:rows迭代行并返回一个表。所以{}是造成问题的原因。

本地数据= {}

for row in db:nrows("SELECT song.id, song.title as song, artist.name as artist FROM song, artist where song.artist_id = artist.id") do
  table.insert(data,row)
end

由于我没有使用Coruna,并且使用不同的lua系统,我无法测试上述内容。

参考:http://lua.sqlite.org/index.cgi/doc/tip/doc/lsqlite3.wiki#db_nrows