V
V
Valery Albertovich Zhmyshenko2020-12-09 00:49:25
Lua
Valery Albertovich Zhmyshenko, 2020-12-09 00:49:25

What is the correct way to delete array elements in LUA?

I want to add objects to my game that would not be pre-specified in level.load, but could be created and deleted directly or indirectly by the player's actions. I think you can add them like this: but how to remove such an object correctly? After all, if it’s just that at some point the length of the array can become very large and I think this can cause problems object[#object+1]=...object[i] = nil

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
dollar, 2020-12-09
@DIvan2000

Instead , it is better to write This is so, by the way. And you can delete with a shift using remove: This will remove the element with index i, as well as shift all subsequent elements by 1 to the left, so that there is no hole in the table as a result. It is believed that this is not the most optimal way to work with arrays. But since this is a built-in function, and Lua itself is written in C, it gets pretty fast within a few hundred elements. Taking into account the fact that game objects will appear / be removed not every tick, but very rarely, this method is quite good. ============================================ Depending on the task, it is possible to optimize its solution in different ways.object[#object+1]=xtable.insert(object, x)
table.remove(object, i)
If a quick search (by key) is important, then it is better to use a unique key instead of a meaningless serial number.
object[x.id] = x
Enumeration of all objects will be possible through pairs. True, without a guarantee of the order in which the enumeration will be: If at the same time you need to calculate the number of all objects somewhere, then this can be done in a separate variable. With this approach, even in the case of faceless indexes, it is possible to increase them to infinity, without worrying about holes, but searching through pairs. In any case, counting the number is not a problem. There are two options for how to do this: a) If the quantity is rarely needed, and the addition / removal occurs frequently, then you can count each time anew:
for k,v in pairs(object) do

local cnt = 0
for _ in pairs(object) do
  cnt = cnt + 1
end

b) If the number needs to be counted frequently, and adding / removing objects is rare, then it is better to update the counter when adding and removing:
objects_cnt = 0 --всегда содержит количество объектов

--добавление
object[x.id] = x;
objects_cnt = objects_cnt + 1;

 --удаление
object[x.id] = nil;
objects_cnt = objects_cnt - 1;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question