0

how can i put my looped value to an array if i have this code?

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
}

but i got this error:

unexpected symbol near 'for'

i just wanted to be look like this...

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

can anyone can help me about my situation or give some advice about it? thanks in advance

2 Answers 2

3

You would have to do something like this, I think:

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

Edit: A question though: Why don't you just specify that in the SQL query and use the results as is? I.e.:

data = db:nrows("SELECT song.id, song.title as song, artist.name as artist FROM song, artist where song.artist_id = artist.id")
Sign up to request clarification or add additional context in comments.

1 Comment

thanks Linus for your answer... about your question, i just want an array for the tableView.lua for my corona sdk..
2

Having looked at the documentation dbn:rows iterates the rows and returns a table. So the {} are what are causing the problem.

local data = {}

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

I have not been able to test the above as I don't have Coruna, and use a different lua system.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.