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

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

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.

1 comment

0

table.insert is for arrays, while you seem to want the Voted table to be a dictionary

1 answer

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)

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