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

Why does this print nil even though the table isn't nil?

Asked by 4 years ago
local UIS = game:GetService("UserInputService")
local Voted = {}
local player = game.Players.LocalPlayer.Name

function Update(Update)
    if Voted[player] then
        print("yep")
    else
        table.insert(Voted, player)
        print(Voted[player])
    end
end

UIS.InputBegan:Connect(function(Key)
    if Key.KeyCode == Enum.KeyCode.A then
        Update("Map1")
    elseif Key.KeyCode == Enum.KeyCode.B then
        Update("Map2")
    end
end)

On the update function, it keeps printing nil on the else statement, even when it has inserted it to the table.

0
table.insert is for arrays, while you seem to want the Voted table to be a dictionary theking48989987 2147 — 4y

1 answer

Log in to vote
0
Answered by 4 years ago
Edited 4 years ago

You're looking for the players name in the table as a dictionary. When you table.insert, it adds a variable.

Try this:

local UIS = game:GetService("UserInputService")
local Voted = {}
local player = game.Players.LocalPlayer.Name

function Update(Update)
    local isOnTable = false

    for i,v in pairs(Voted) do
        if v == player then
            isOnTable = true
        end
    end

    if isOnTable == true then
        print("the players name is on the table")
    else
        table.insert(Voted, #v+1, player)
        print("player has now been added to the table")
    end
end

UIS.InputBegan:Connect(function(Key)
    if Key.KeyCode == Enum.KeyCode.A then
        Update("Map1")
    elseif Key.KeyCode == Enum.KeyCode.B then
        Update("Map2")
    end
end)
Ad

Answer this question