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?
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