lua中的for循环如何使用数组索引

如果我有这段代码,我该如何将循环变量放入数组中?

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"
 }
...
}

是否有人可以帮助我解决这个问题或给出一些建议? 提前致谢。

原文链接 https://stackoverflow.com/questions/10548018

点赞
stackoverflow用户295262
stackoverflow用户295262

我想你需要这样做:

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")
2012-05-11 08:46:37
stackoverflow用户438753
stackoverflow用户438753

在查看文档后,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

2012-05-11 08:53:07