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

Table attempt to call a nil value?

Asked by 3 years ago

I'm working on a car value check script and I don't want to use too many if statements so I'm trying to use functions in tables. My problem is on line 29:

local PlayerGui = game.Players.LocalPlayer:WaitForChild("PlayerGui")

function PlayerAdded(player)
    local leaderstats = player:WaitForChild("leaderstats")
    local String = leaderstats:WaitForChild("items").Value
    local Table = String:split(" ")

    local function keys(tbl)
        local tblKeys = {}

        for k, _ in pairs(tbl) do
            tblKeys[#tblKeys + 1] = k
        end

        return tblKeys
    end

    local Cars = {
        ["ATVTrue"] = function()
            print("you have ATV")
        end,
        ["TruckTrue"] = function()
            print("you have Truck")
        end
    }

    for count = 1, #keys(Cars) do
        if Table[count] == keys(Cars)[count] then
            Cars[count]() --Problem
        end
    end

    --[[
    PlayerGui.CarSpawner.ScrollingFrame.Truck.Purchase.Visible = false
    PlayerGui.CarSpawner.ScrollingFrame.Truck["Padding(pur)"].Visible = false
    --]]
end


game.Players.PlayerAdded:Connect(PlayerAdded)
for i,v in next,game.Players:GetPlayers() do
    PlayerAdded(v)
end

I get this error message:

ReplicatedFirst.Gui:29: attempt to call a nil value 

How can I get the functions to work and how is the value nil?

1 answer

Log in to vote
1
Answered by
Ziffixture 6913 Moderation Voter Community Moderator
3 years ago
Edited 3 years ago

By the context of your for loop, count refers to a numeric iteration; no such key exists in Cars.

The logic you intended to use is:

local VehichleKeys = keys(Cars)

for Index = 1, #VehichleKeys  do
    if (Table[Index] == Index[Index] then
        Cars[VehicleKeys[Index]]() 
    end
end

However, this approach is too extravagant. I suggest revising your program to:

local Cars = {
    ["ATVTrue"] = function()
        print("You have ATV")
    end,
    ["TruckTrue"] = function()
        print("You have Truck")
    end
}


for Key, Function in pairs(Cars) do
    ---------------
    if (table.find(Table, Key)) then
        ---------------
        Function()
    end
end
0
Thanks couldn't wrap my head around my method Darksniper600 104 — 3y
Ad

Answer this question