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

How can you reference a value inside of a table?

I have this code but this didn't work at all. Example code:

local ExampleTable = {"Player1Name", "Player2Name"}

script.Parent.MouseButton1Click:Connect(function()
	if ExampleTable[game.Players.LocalPlayer.Name] then
		--Do this 
	else
		--Do this
	end
end)

Im basically trying to see if a player's name is inside of my local table.

2 comments

0

i think its cuz ur putting Player1Name, Player2Name instead of Player1, Player2 ?

0

I put that because I'm saying "This is where the player's name goes". In the actual game it is the correct name

1 answer

✓ Accepted answer

A table (known as an array in most programming languages) is a list of values (which you already know) called elements. To set/read data from the table you use the following format Table[i] where i is the spot in the table you wish to set or read. so what you want is something like this

for i,v in ipairs(ExampleTable) do
	if v == game.Players.LocalPlayer.Name then
		--Do this
	else
		--Do this
	end
end

i counts how many elements in the table it has found and v is the value of the element it is checking.

3 comments

0

Thank you for reminding me! I totally forgot about for iv in pairs loops!

0

While it may seem like a nitpick, I'd like to point out that tables are not the same as arrays in other languages. It's very important to remember that any non-nil value can be both a key and value in Lua.

0

yes but are there any other array types in lua? So while there may be other tables may be different than arrays in different languages I think that tables in lua are similar to arrays in other languages. Although it might just be the same as all of the array like objects. (I posted this back before I had learded any other languages)

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