Search code examples
luaroblox

How do you get the item's index with i, v in pairs


I am trying to make a game, and I am trying to random an item in the table, so I used i,v in pairs, but It only gives me the name of the item, how do I get the item? It is a function. Can anyone knows the answer and tell me, thank you.

The code I scripted down there

for i,v in pairs(TTH) do -- Making the for loop
    TTH.     -- Didn't know what to do
end -- Ending of for loop

I scripted it and searched up there and finds nothing, a table can't use FindFirstChild so can anyone tell me what to do?


Solution

  • Lua for loops are implemented in this way:

    for i, v in pairs(table) do
      -- i: index
      -- v: value
    end
    

    If you were doing a for loop, you'd be iterating over each instance inside TTH (TTH would have to be a table) which is not the intended behavior.

    Let's say you had a folder named TTH and wanted to get a random child in that folder each time the script was executed. You would want to do:

    local childTable = TTH:GetChildren()
    local child = items[math.random(1, #children)]