-
I want to assign the player’s backpack to a variable
-
The issue: The “or” operator is not returning the second expression when the first expression is nil aka false:
lua local player = game.Players.LocalPlayer local backpack = player.Backpack or player:WaitForChild("Backpack")
18:52:14.274 Backpack is not a valid member of Player “Players.Invisible_Humanoid” - Client - LocalScript:4 -
I have tried the alternative which is
lua local backpack = player:WaitForChild("Backpack")
and it works fine with no errors. But I still want to figure out why my code doesn’t work.
Why would you do player.Backpack or player:WaitForChild("Backpack")
if you are assuming it won’t be loaded? Just use
I am not sure why you aren’t satisfied with that. That is what you want.
If the BackPack is already valid, the chunk will result in an infinite yeild
That is not correct, Instance:WaitForChild
just returns the child if it exists already.
Can u give me the source where u learned this
For clarification, the or
operator in this case fails because game.Players.LocalPlayer
is a userdata
value which do not behave like tables by default.
Roblox has specifically designed it so indexing objects with something that doesn’t exist will error instead of returning nil like a table. This means that your code will never pass the left side of the or
before erroring, assuming that the Backpack doesn’t exist yet.
incapaz already gave you the best solution here but I’ll restate it. Just shorten the code to:
local player = game.Players.LocalPlayer
local backpack = player:WaitForChild("Backpack")
You wont run into issues with infinite yielding because as incapaz said, if the object exists already it will not yield. Even if the console spits out the warning for an infinite yield, the code does not stop yielding until it finds the object. Either use the second argument to WaitForChild
or simply ignore the warning if players are loading too slow.