【问题标题】:for loop in lua how to index with arraylua中的for循环如何用数组索引
【发布时间】:2012-05-19 20:28:20
【问题描述】:

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

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

谁能帮助我了解我的情况或提供一些建议? 提前致谢

【问题讨论】:

    标签: arrays for-loop lua coronasdk


    【解决方案1】:

    我认为你必须这样做:

    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")
    

    【讨论】:

    • 感谢 Linus 的回答...关于您的问题,我只想为我的 corona sdk 的 tableView.lua 提供一个数组..
    【解决方案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

    【讨论】:

      猜你喜欢
      • 2020-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多