Help looping through a subtable

I’m not sure subtable is the 100% correct terminology but it fits logically, anyways I don’t usually work with tables and decided to incorporate some. However I can’t for the life of me figure out how to iterate through my subtables.

My Code looks something like this:

local table = {
    {tip = blah,blah,blah}
    {tip = blah,hmm,blah}
    {tip = hmm,blah,blah}
}

local tip = math.random(1,3)

--I would like to iterate through the randomly selected "tip"

--I tried the following

for i, v in ipairs(table[tip]) do
     print(v)
end

--Which did not work

I looked it up and only found people wanting to iterate through everything not a specific entry in the table, any and all help is appreciated :slight_smile:

The problem is with your use of ipairs. Instead just use plain ole pairs as there is no numerical index to your table.

table is a keyword, change that variable to something like t to avoid any weird issues related to that.

Also your table structure doesn’t make any sense, you have a string key that references values seperated by commas that aren’t inside a subtable, I think that isn’t possible. Instead you either want to do:

local t = {
	{tip = {blah,blah,blah}}, --don't forget the commas when listing values!
	{tip = {blah,hmm,blah}},
	{tip = {hmm,blah,blah}}
}

And index it like this:

for i, v in pairs(t[tip].tip) do
	print(i, v)
end

Or you want to do:

local t = {
	{blah,blah,blah}, 
	{blah,hmm,blah},
	{hmm,blah,blah}
}

and index it like that:

for i, v in pairs(t[tip]) do
	print(i, v)
end

Lastly keep in mind that hmm and blah must be variables or they will error your code, if they’re strings you must surround them with " or ', so they become "hmm", "blah", etc.

Don’t worry the table isn’t actually called table I just wrote similar example code out your first supplied method worked thanks!

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.