How do I index a table value with an in pairs loop?

This is most likely a simple issue, but I’m just trying to learn.

I have 4 values in my table. How do I print the 1st, 2nd, 3rd, and 4th value of that table with an in pairs loop?

	for a,b in pairs(SavedAnswers) do
		print("SavedQuestion1Text: "..b[1])
		print("SavedQuestion2Text: "..b[2])
		print("SavedQuestion3Text: "..b[3])
		print("SavedQuestion4Text: "..b[4])
	end

Output Error

attempt to concatenate field '?' (a nil value)

I just realized that would print all of those 4 times. Just ignore that for now.

1 Like

If SavedAnswers is the table you’re talking about, a and b already are they indices and values in the table.

local SavedAnswers = {"a", "b", "c", "d"}
for a, b in pairs(SavedAnswers) do
	print(("SavedQuestion%dText: %s"):format(a, b))
end
2 Likes
local SavedAnswers = {"hello","hi","oh","welcome"}

for i, v in pairs(SavedAnswers) do
    print(v)
end

i = index
v = value

print(i) =

Output:

1
2
3
4

print(v)

Output:

hello
hi
oh
welcome

The index,is the position of something in a table.(1,2,3 and keep going.)
The value, is what contains in the index.(The data)

2 Likes

Off what I can see you made a mistake. B in your loop is the actual values in your table. So what you are trying to do is that you are printing value 1 of value and that is wrong. You don’t have to access each valu individualy cuz the table do that to you automatically. Remover these things in you script [1] [2] etc and just print once