0

如果我有此代码,如何将循环值放入数组?

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

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

4

2 回答 2

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 查询中指定它并按原样使用结果?IE:

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-11T08:46:37.320 回答
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

于 2012-05-11T08:53:07.647 回答