[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Definition of table.insert
- From: Dirk Laurie <dpl@...>
- Date: Fri, 31 Dec 2010 11:21:19 +0200
The examples below were given by Greg Falcon in another thread.
> t={1,2,3}; table.insert(t, 1, nil)
> for i in pairs(t) do print(i) end
2
3
4
> t={1,2,3}; table.insert(t, -42, 'x')
for i in pairs(t) do print(i) end
2
3
4
-42
Is this the intended behaviour? Let's turn to the official docs.
"Programming in Lua" says:
The table.insert function inserts an element in a given position
of an array, moving up other elements to open space.
The 5.2 Reference Manual says much the same, but adds "if necessary."
It also says at the start of the section:
Most functions in the table library assume that the table
represents an array or a list.
So, there is some reason to suppose that the observed behaviour is
a side-effect of the implementation, rather than carefully planned
intentional behaviour.
Is this desirable behaviour? Here is another example:
> t={1,2,3}; table.insert(t,-1e8,nil)
It takes about 18 seconds on my machine. (About 3 seconds using
LuaJIT).
Is this intentional or a side-effect of the implementation?
A final example:
> t={1,2,3}; k=-42; table.insert(t,k,1); table.remove(t,k)
> for i in pairs(t) do print(i) end
2
3
4
-42
Thus, table.remove won't remove something that table.insert
has inserted.
Suggestion:
"if necessary" should mean that inserting something into
an empty position k does the same as assigning it to t[k].
Dirk