Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

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

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)

2 comments

0

You don't use numbers there and I is not defined. Please reconsider what your pseudocode is trying to describe.

0

yeah sorry, i was a bit lazy when i wrote this

1 answer

✓ Accepted answer

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

2 comments

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.

0

No problem!

This discussion is preserved as it was. New answers, comments, and votes are closed.