Function that returns table

I have a db.lua file that I am using to encapsulate a simple sqllite database of one table. Among other things, it contains a function that returns all rows of the table:

 

require “sqlite3”

 

local db = {}

 

local database

 

– snip

 

function db.getAllRows()

return db.database:nrows("SELECT * FROM "  … tableName)

end

 

return db

In main.lua I populate a list view like so: (note the loop header in bold italics)

local function populateListView(tv)

tv:deleteAllRows()

for row in db.getAllRows() do

local rowParams = 

{

id = row.id,

name = row.name

}

tv:insertRow{params = rowParams}

end

end

This works with no problem, but when I try to handle the rows as an array/table (change in bold italics) I get an error message saying that I am trying to index a function value:

local function populateListView(tv)

tv:deleteAllRows()

_ local allRows = {} _

allRows = db.getAllRows()

_ for i = 1,#allRows do _

local rowParams = 

{

id = allRows[i].id,

name = allRows[i].name

}

tv:insertRow{params = rowParams}

end

end

I thought that db.getAllRows() returned a table of rows? Apparently inserting the function call directly into the for loop header is OK but trying to index the returned table/array is not? Or maybe allRows is the function and not the value returned by the function?

By the way, the reason I want to use the second approach is to get the table of rows first and then do something to the rows before inserting them into the table view.

db:nrows doesn’t return a table, it returns an iterator.  In the first example you are using the for loop in iterator mode:  for X in ITERATOR.  In your second example, you’re using the for loop in Index mode where a number gets incremented by one.  If you want your getRows() function to return a table, you will need to do something like:

function db.getAllRows()

          local t = {}

for r in db.database:nrows("SELECT * FROM "  … tableName) do

      t[#t+1] = r

end

return t

end

 

 

or something like that.

Excellent! That was just it. I had not realized that an iterator was returned and not an actual table.

db:nrows doesn’t return a table, it returns an iterator.  In the first example you are using the for loop in iterator mode:  for X in ITERATOR.  In your second example, you’re using the for loop in Index mode where a number gets incremented by one.  If you want your getRows() function to return a table, you will need to do something like:

function db.getAllRows()

          local t = {}

for r in db.database:nrows("SELECT * FROM "  … tableName) do

      t[#t+1] = r

end

return t

end

 

 

or something like that.

Excellent! That was just it. I had not realized that an iterator was returned and not an actual table.