Accessing Tables

So I’m pretty new to lua and programming in general, and I’m having a lot of trouble with tables. I’m working on an app that downloads xml files and converts them into a news app. I’ve understood tables to be like structs in c++. How can a save a list of tables in lua, as I would have an array of structs in c++

The issue that I am having Is once I create a table that has a title, body, and image; I cant access it anymore. How can I iterate trough the tables in the class?

Yes, you’re right, tables can be used like a struct in C.  And tables can also be used like an array.  And since you can nest tables indefinitely, you can create an array of structs like this:

[lua]

local myArray = {}

for i=1,10 do

   – There’s no need to actually define myStruct here; these two lines could be collapsed into one.  I just separated them into two to emphasize how we’re creating an array of structs

   local myStruct = {title=“some title”, body=“some body”, image=“filename.png”}

   myArray[i] = myStruct

end

[/lua]

And you could iterate through the array like this:

[lua]

for i = 1,10 do

   print(myArray[i].title, myArray[i].body, myArray[i].image)

end

[/lua]

Hope this helps.

  • Andrew

Yes, you’re right, tables can be used like a struct in C.  And tables can also be used like an array.  And since you can nest tables indefinitely, you can create an array of structs like this:

[lua]

local myArray = {}

for i=1,10 do

   – There’s no need to actually define myStruct here; these two lines could be collapsed into one.  I just separated them into two to emphasize how we’re creating an array of structs

   local myStruct = {title=“some title”, body=“some body”, image=“filename.png”}

   myArray[i] = myStruct

end

[/lua]

And you could iterate through the array like this:

[lua]

for i = 1,10 do

   print(myArray[i].title, myArray[i].body, myArray[i].image)

end

[/lua]

Hope this helps.

  • Andrew