Need help in understanding the generic for loop

Was watching a tutorial and the person wrote this code

local playerItems = {
 Josh = {"Crossbow", "Axe"}
 Jeff = {"Sword", "Shield"}
}

for name, items in playerItems do
  for index, value in items do
   print (name.." - "..value)
end
end

I looked at it a bunch of times and have no idea what these variables do and what corresponds to what

I would appreciate help

So basically “for name, items in playerItems” goes through the playerItems table, which has “Jeff” and “Josh” in them. Both have their own table with items in them as you can see. The loop then takes their tables, which you’ve called “items”.

The next for loop, “for index, value in items”, does pretty much the same thing as the one above. It takes the content of the tables Jeff and Josh have.

The print function then basically says which of these two have which items in their own tables.

I hope this kind of cleared it up, I did my best to explain it as good as possible!

2 Likes

Thanks a lot! but just so I confirm my understanding…

First, I can replace the “name” and “items” with anything else right?

Second , name corresponds to “Josh” and “Jeff” while items corresponds to whatever’s in their table, right?

Yes you can, they are simply variables that can be named anything, as long as it’s valid.

1 Like
local playerItems -- a variable
{ } -- array/table
Josh = {"Crossbow", "Axe"} -- Josh is a variable inside the playerItems table; Crossbow and Axe are two items inside Josh's table

What the table looks like:
playerItems

  1. Josh
    a. Crossbow
    b. Axe
  2. Jeff
    a. Sword
    b. Shield

for anyVariableForIndex(each), anyVariableForIndex’sItem(stuff) in playerItems’sTable do -- returns 1 & 2 which are Josh & Jeff
for anyVariableForIndexAgain(each), anyVariableforIndex’sItemAgain(thing) in stuff do -- returns a & b which are the weapons names
print(Josh & Jeff - theirThings)
end -- close the a&b loop through
end -- close the 1&2 loop through

Inside the table, don’t forget to use a comma if there will be more than one item or it will throw an error.

local playerItems = {
 Josh = {"Crossbow", "Axe"}, -- comma here
 Jeff = {"Sword", "Shield"}
}
1 Like

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