How to output a specific value from an array?

I want to create a script where whenever the player triggers the proximityPrompt it will cause it to read the string from the selectedCrate variable in the table Crate, after reading the selectedCrate variable it will iterate through the Crate table and when the value in the table that it’s iterating through matches selectedCrates string(in this case “AnotherBoat”) it will assign it to the value (finalCrate) and finally print the output finalCrate which should be:
OUT: “AnotherBoat”
I’m sure this isn’t the most efficient but I’m not bothered for efficiency as this is for a side-project.

The comment is an attempt I made, I didn’t expect it to function well because I don’t understand it but I felt it necessary to leave it in, the output I got from the attempt was: ‘2’ as its index in the array is two so instead of outputting the value it output the index of the value.

local players = game:GetService("Players")
local proxPrompt = script.Parent.ProximityPrompt
local _player 
local selectedCrate = "AnotherBoat"
local Crate = {"BeginnerBoat", "AnotherBoat", "YetAnotherBoat"}

local function onPlayerAdded(player)
	_player = player
end
players.PlayerAdded:connect(onPlayerAdded)


function AssignCrate(obj, finalCrate)
for i, value in ipairs(Crate) do 
		print(i, value)
		if i == selectedCrate then 
			local finalCrate = i
		end
		print(finalCrate)
	end
	-- Another failed attempt: local chosenCrate = table.find(Crate, selectedCrate)

	end
proxPrompt.Triggered:Connect(function()
	print("Triggered")
	AssignCrate()
	end)

The reason it outputs the index is your comparing the index to the value. You should compare the key instead of the index.

function AssignCrate(obj, finalCrate)
for i, value in ipairs(Crate) do 
		print(i, value) -- i would return the index, value is the key
		if value == selectedCrate then -- comparing key to key
			local finalCrate = value -- final crate is the value that satisfies the comparison
		end
		print(finalCrate)
	end
	-- Another failed attempt: local chosenCrate = table.find(Crate, selectedCrate)
end
1 Like

I presumed I was making a basic mistake, I appreciate the help as it’s functional now.

1 Like