Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How to get an object from a table, based on its index? (in an efficient way)

Asked by 7 years ago

please note I want this done to be with the least amount of lines used as possible, I understand theres an easy solution using a straight-forward method to do this otherwise.

player = game.Players.LocalPlayer
char = player.Character
backpack = player.Backpack
tools = game.Lighting.Tools:GetChildren()

part = game.Workspace.Part

part.Touched:connect(function()



    for i, v in pairs(tools) do

        local numbers = math.random(1, #tools)

        if v == v[I] then

            v:clone()

            v.Parent = backpack



        end
    end
end)

so clearly that wouldn't work, so what is the simplest way (or best way) to take an object from a table, based on its index within the table? for example, I have a math.random call. for the number it picks out, I want that to determine which object will be selected (using that objects index in relation to the number)

0
You don't use numbers there and I is not defined. Please reconsider what your pseudocode is trying to describe. User#6546 35 — 7y
0
yeah sorry, i was a bit lazy when i wrote this ProgramsMan 100 — 7y

1 answer

Log in to vote
1
Answered by 7 years ago

I believe what you want is this, but I'm not sure, as your question is slightly hard to understand:

local tab = {}
local number = math.random(1,#tab)
tab[number] -- would return  the value

So, to incorporate that into your code:

local player = game.Players.LocalPlayer -- made them locals because locals are faster and better
local char = player.Character
local backpack = player.Backpack
local tools = game.Lighting.Tools:GetChildren()
local part = game.Workspace.Part

part.Touched:connect(function()
    local number = math.random(1,#tools)
    local clone = tools[number]:Clone() -- clones the tool
    clone.Parent = backpack
end)

TIP:

Use Tab to format your code, not space, as it is inconsistent.


Hope I helped! If you need help, feel free to ask.

~TDP

0
well I tend to use tab of course, but anyways thanks for the answer. but I suppose what I also wanted was an object from the table, if its index was equal to the math.random output. but anyways this does solve in part what I wanted to know. ProgramsMan 100 — 7y
0
No problem! TheDeadlyPanther 2460 — 7y
Ad

Answer this question