coffeemonitor
coffeemonitor

Reputation: 13120

Lua tables and iterating

Does this look right?

local data = {}

for i = 1, 22 do
  table.insert( data, data[i].title = "A title here")
end

I get a syntax error in the insert(), and I'm not sure what's causing it. I'm guessing data[i].title isn't correct.

Upvotes: 2

Views: 179

Answers (2)

lhf
lhf

Reputation: 72312

Why use table.insert at all when this is so much clearer?

for i = 1, 22 do
   data[i]= {title = "A title here"}
end

Upvotes: 3

Alex
Alex

Reputation: 15313

I think this is what you're trying to do:

local data = {}

for i = 1, 22 do
  local newdata = {
    title = "A title here"
  }
  table.insert(data, newdata)
end

data[i] will be nil until you create a new table and assign it there. Also, it looks like you're either trying to insert the title into data or trying to insert a new table into data, it's hard to tell which. My example is assuming you're trying to make a new table, assign a title to it, and put that new table in data.

Upvotes: 3

Related Questions