Questions about ModuleScripts: Strange, unintended behavior?

No you can’t do it any faster than pairs. If you didn’t want to use next you could keep each index in a hashmap if you manually updated the hashmap but I don’t know why you’d do that since it would make it harder to code and probably still slower (although faster than a next iterator). There isn’t a way around this (pairs will always be the fastest way to iterate over a string indexed loop) and in the new VM pairs is much faster anyway. The only time I’d think there would be a noticeable difference is when you’re iterating over millions of items or something ridiculous.

So if I understand, if my game had 2 teams, each 100 NPCs that fight each other, etc.
Using pairs should be fine for looking for the closest target?
Is that the best way to do it?

Keep in mind that 200 NPCs would cycle through each other’s teams to find the nearest target.

Also about quick deleting,
What would be a quick way to delete something from the tables?

I’ve seen something before like setting the index of the npc to the index of the last npc’s index (basically switching positions) and then
setting the last index to nil, but I am unsure how that works.

Also pretty sure I can’t use table.remove() since my table has no number indexes.

A quick way to delete something from the table is to simply set the value at an index to nil. You might have noticed pairs and ipairs ignore indexes which have a nil value (since they are actually removed from the table). Also as noted before ipairs doesn’t go over gaps. So if you have something at index one and something at index three it will stop at index one since there is nothing at index 2.

Example:
table["index1"] = nil

But if I set a value to nil.
Won’t the variable technically still be there actually…?
I feel like as if the variable would still exist
but just gets skipped.
Won’t this eventually fill up memory?
Isn’t this like doing

local variable = nil

Or is this different in tables? Do empty variables get auto-removed?

Empty variables will be removed since nil can’t hold references (it’s just the absence of a reference). All local variables will be cleaned up when the thread (and all child threads) which references them ends.

Correction: local variables are cleaned up as soon as they go out of scope. If they are referenced somewhere outside of the scope and are a gc-able object (such as a dynamic string or a table), the value will live for as long as it is referenced.

1 Like