Jump to content
Alloder.pro  about Allods with love 😱
Search In
  • More options...
Find results that contain...
Find results in...

Servers monitoring and the Addons Editor

We present you two legends. All dreams come true.

Servers monitoring The Addons Editor

Digest April

We talk about what was done and updated in the past month. We help keep abreast of events.

Read more

Game tooltips

Tooltips provide a way for 3rd party fansites and extensions to display detailed information on mouseover.

Read more

как удалить запись из таблицы


icreator
 Share

Recommended Posts

если в таблице все индексы - строковые??

Code:
---- должна удалять строку из таблицы но не удаляет (

function removeRow(t, key)

researchObj("",t)

local i = 0

for k, _ in pairs(t) do

if k == key then

LogInfo("removing ", k)

table.remove (t,i)

end

i = i + 1

end

researchObj(" --- ",t)

end

Link to comment
Share on other sites

table.remove() работает ТОЛЬКО с теми таблицами, которые обслуживаются исключительно с помощью table.insert() и table.remove(). Дело в том, что в Lua, на самом деле, таблица может быть устроена по-разному. Если таблицу формируют ТОЛЬКО с помощью table.insert() и table.remove(), то такая таблица представляет из себя очень простой и быстрый, классический массив (с числовыми индексами от 1 и далее), и работает очень быстро, почти как массивы в языке Си.

Но, когда нужно использовать какие-то другие индексы (например, строки), или числа, но не по порядку (например, ID игроков) то таблицу создают БЕЗ помощи этих двух функций. Новые элементы таблицы создаются так: Таблица [ Индекс ] = Значение, а удаляются так: Таблица [ Индекс ] = nil В таких случаях, таблица уже НЕ обычный массив, а ассоциативный массив - совсем другая, более сложная структура, в которой индексами может служить чуть ли не всё что угодно.

Кстати, если пользователь создавал массив с помощью table.insert(), а потом, внезапно, влез грязными ручками, и вставил такой индекс, какие вставляются только в ассоциативные массивы, то Lua "на лету", незаметно, сконвертирует этот классический массив в ассоциативный массив. Это Lua умеет. Но никогда не будет обратного пути - ассоциативный массив навсегда останется таковым.

Code:
function removeRow(t, key)

t [ key ] = nil

end

Link to comment
Share on other sites

спасибо. а я просто стала новый массив создавать с переприсваиванием.. может и зря

Code:

---- создает новуб стабицу - без одной строки, найденой по ключу

function removeRow(t, key)

local tNew = {}

for k, v in pairs(t) do

if k ~= key then

tNew [k]  = v

end

end

return tNew

end

Link to comment
Share on other sites

Вот это, совершенно точно, зря. Так аддон делает совершенно лишнюю и ненужную работу.

Убери-ка ты лучше эту функцию, а вместо всех её вызовов

Code:
removeRow( таблица, индекс )

напиши так:

Code:
таблица [ индекс ] = nil
Link to comment
Share on other sites

про nil = вроде как не удаляется само поле... судя по этому:

Quote:

2.9.2 - Weak Tables

A weak table is a table whose elements are weak references. A weak reference is ignored by the garbage collector. In other words, if the only references to an object are weak references, then the garbage collector will collect that object.

A weak table can have weak keys, weak values, or both. A table with weak keys allows the collection of its keys, but prevents the collection of its values. A table with both weak keys and weak values allows the collection of both keys and values. In any case, if either the key or the value is collected, the whole pair is removed from the table..

тоесть поле будет уничтожено но не сразу.. понятно в принципе

Link to comment
Share on other sites

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

×
×
  • Create New...

Important Information

By using our site you agree to the Terms of Use