Table.insert & # 8594; remember the key of the inserted value
I am inserting the value of a variable into a table and want to make sure the action is successful. So I want to return a value, but not var, but from a table.
Is there an easier way to iterate over the table?
Some way to remember the key of the value in the table while it is inserted?
function(value)
for _,v in pairs(theTable) do
if v == value then
return --(due the table already contains the value)
end
end
table.insert(theTable, value)
return -- table.[VALUE]
end
+3
source to share
1 answer
local ix = #theTable + 1
theTable[ix] = value
Here's what it does table.insert
:
As a special (and frequent) case, if we call insert out of position, it inserts the element at the last position of the array (and therefore does not move the elements)
As a by-product, your function is rather inefficient; you are doing a O(n)
"contains" check , which can be done much better if you create an index on the values.
+4
source to share