Hi all,
I’m a beginning scripter, and have come across a fairly technical issue that I would like to get resolved before I proceed with continuing to write code for my game. This issue at hand is basically this. Say I have some variable, target
, which has as its value some humanoid that an NPC should be targeting. Now, if this humanoid were to die, I want this NPC to immediately forget about the target and search for a new one. Using something like
target.Died:Connect(function()
target = nil
end)
would achieve that effect. But if I had passed target
into some other function, because variables are passed by value, that function wouldn’t notice the change. So, for example, say I have this:
function main()
local target = searchForTarget()
target.Died:Connect(function()
target = nil
end)
moveToTarget(target)
end
Say I’ve run main()
, I’ve found a target with searchForTarget()
, and now the NPC should be moving to that target with moveToTarget()
, where target
is passed in as an argument. Now suppose target.Died
fires while the NPC is moving to the target. Well, moveToTarget()
is going to continue using the original value of target
, which is not what I want.
The solution to this problem to me would seem to be the following:
target = nil
function main()
target = searchForTarget()
target.Died:Connect(function()
target = nil
end)
moveToTarget()
end
and now within moveToTarget()
I can now run a check like if not target then return end
to get the function to stop.
However, there seems to be almost a universal consensus among programmers that using variables in this way is very bad, and I do (sort of) understand the reasons, but I just can’t see what else I’m supposed to do in this instance. It’s also very likely that I’ve misunderstood something (again, I’m new to Lua and coding altogether), so if anyone could shed some light on this topic for me, I’d very much appreciate it!