Looping through array

Hey fellow devs,

I am trying to run through the array Part1 however I just get the error table expected, got string
Here is what I have so far:

Part1 = {6,8,2,4}

for _, owned in pairs(ownedPlots) do
	print("owned".. owned)
			
	for _, adjacentToOwned in pairs(owned) do 
				
		print(adjacentToOwned)
				
	end
end

The print outputs owned Part1

Thanks in advance :slight_smile:

1 Like

You say you want to iterate over the Part1 array, yet you’re not using it anywhere else in your code?

-- Print each value in the array Part1
Part1 = {6,8,2,4}

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

You’re likely getting the error table expected, got string because (my guess) owned is a string, not a table.

2 Likes

When you are iterating through the table Part1, the owned variable will return a string, which then you are trying to iterate over, which is not possible as you can only iterate over a table.

1 Like

So how would I make it itterate over it?

Can you post the section of code, which contains the ownedPlots table?

1 Like

It is part of a data store with the format “Part1” "Part2"etc. I would post more code but I have just turned my PC off.

Not much I can really do to help then at the moment, until I can see a snippet of the code which defines the ownedPlots table, so once you’ve posted it I’ll be back :slight_smile:

1 Like

Your issue seems to be that ownedPlots is an array full of strings. Whenever it prints “owned Part1”, you don’t actually check the type of it. Part1 is actually a string. You can tell Part1 isn’t an array, because if it was, it’d print “table: some_random_letters_here”

If you want to turn that string into the Part1 variable, you’ll have to use an if statement.
EG:

if (owned == "Part1") then
	owned = Part1; -- Part1 = array reference;
elseif (owned == "Part2") then -- etc
2 Likes

I’m assuming you want to iterate a table called Part1 when your first loop encounters a value "Part1" in ownedPlots. What you should do is create a table of tables (a dictionary) where you put tables like Part1, Part2, etc. to be able to index them easily:

local list = {
    Part1 = {6,8,2,4},
    Part2 = {1,2,3,4}
}
for i, owned in pairs(ownedPlots) do
    local vals = list[owned]
    if vals then
        for i, adjacentToOwned in pairs(vals) do
            print(adjacentToOwned, "is adjacent to", owned)
        end
    end
end

(forgive any mistakes, I typed this on mobile)

1 Like