Jump to content

Random item in table


iPanda

Recommended Posts

Posted (edited)

Hello everyone. I have a problem when creating points with objects for inventory. I want to show a random item (or several items) from my table to output them at the point items.

Table:

itemTable = { 
    ["Loot"] = { 
        {"Item1",1}, 
        {"Item2",1}, 
        {"Item3",1}, 
        {"Item4",1}, 
        {"Item5",1}, 
        {"Item6",1}, 
    }, 
} 

I also tried to get a random item with the help of this string, but gives me an error that string. Please help, thanks in advance с:

itemTable["Loot"][1][math.random(1,#itemTable["Loot"])] 
  
--or 
itemTable["Loot"][math.random(1,#itemTable["Loot"])] 
  

Edited by Guest
Posted
itemTable.Loot[math.random(1,#itemTable.Loot)] 

This will return a 'Loot' table, so 'result[1]' would be "ItemX"

Posted
itemTable.Loot[math.random(1,#itemTable.Loot)] 

This will return a 'Loot' table, so 'result[1]' would be "ItemX"

it also does not provide a random list of items and output an error in the console.

Posted

This will return a table as I said, so if you want to retrieve the 'Item..' string use the index on the result.

itemTable.Loot[math.random(1,#itemTable.Loot)][1] -- like so 

Posted

TiM3, thank you very much, everything works! But I have another question, how can I get a few items at once (after all, this function gives only 1 point thing)?

Posted
  
local ind1, ind2 = math.random(1,#itemTable.Loot), math.random(1,#itemTable.Loot) 
if ind1 == ind2 then 
    if ind1 == 1 then 
        ind1 = math.random(2,#itemTable.Loot) 
    elseif ind1 == #itemTable.Loot then 
        ind1 = math.random(1,#itemTable.Loot-1) 
    else 
        ind1 = math.random (0,1) == 1 and math.random(1,ind2-1) or math.random(ind2+1,#itemTable.Loot) 
    end 
end 
  
-- then use 
itemTable.Loot[ind1][1] 
itemTable.Loot[ind2][1] 
  

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...