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

How can you reference a value inside of a table?

Asked by 6 years ago

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.

0
i think its cuz ur putting Player1Name, Player2Name instead of Player1, Player2 ? ATestAccount420 31 — 6y
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 MusicalDisplay 173 — 6y

1 answer

Log in to vote
2
Answered by 6 years ago

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.

0
Thank you for reminding me! I totally forgot about for iv in pairs loops! MusicalDisplay 173 — 6y
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. Avigant 2374 — 6y
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) justoboy13 153 — 6y
Ad

Answer this question