Hello, I've been trying to create an inventory system where it will redraw GUI every time the descendants of the inventory folder has been changed. I created a function to do this in a LocalScript called RedrawGrids(), but when I tried to call it using a MouseEnter I receive the following error in the output:
06:02:49.260 - Players.Rheines.PlayerGui.NewInventory.MainFrame.Inventory.Padding.LocalScript:9: attempt to call global 'RedrawGrids' (a nil value)
This is my script:
local PlayerService = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Player = PlayerService.LocalPlayer
local Equipped = Player:WaitForChild("Equipped")
local Inventory = Player:WaitForChild("Inventory")
--Currently use MouseEnter to check if it works.
script.Parent.MouseEnter:Connect(RedrawGrids())
--Redraw inventory grids.
function RedrawGrids()
print('entered function')
--Clear all gui to redraw with updated inventory.
for _,guis in pairs(script.Parent:GetChildren()) do
if guis:IsA("ImageLabel") then
guis:Destroy()
end
end
--Redraw inventory contents.
for _,gear in pairs(Inventory:GetChildren()) do
local gui = ReplicatedStorage.ItemGUI:Clone()
gui.Name = gear.Type.Value
gui.Parent = script.Parent
end
end
However, when I made RedrawGrids into an anonymous function such as
script.Parent.MouseEnter:Connect(function()
print('entered function')
--Clear all gui to redraw with updated inventory.
for _,guis in pairs(script.Parent:GetChildren()) do
if guis:IsA("ImageLabel") then
guis:Destroy()
end
end
--Redraw inventory contents.
for _,gear in pairs(Inventory:GetChildren()) do
local gui = ReplicatedStorage.ItemGUI:Clone()
gui.Name = gear.Type.Value
gui.Parent = script.Parent
end
end)
it works perfectly fine. However, I want to call RedrawGrids as a variable so that I can reuse it as often as I like. Is there something that I did wrong?

2 comments
You're calling the function before you define it on Line 9.
The issue is that in your first attempt - function RedrawGrids doesn't exist when you try to use it. In your second attempt - it works because you are hooking MouseEnter directly to the events you want to happen. To circumvent this, create the RedrawGrids function before you try to hook it to an event.