A table is a list only if its indices are consecutive: t[1], t[2], t[3], ... t[i], ... t[N] are non-nil for all i from 1 to N. Your code is using a table as an associative array (map in C++, dictionary in Python), so the table operations won't work (actually, they might work sometimes, since it is undefined behavior). From the Lua 5.1 ref manual:
Most functions in the table library assume that the table represents an array or a list.
Unfortunately the ref manual does not explicitly define "array or list", but browsing the ref man where it discusses arrays indicates that two simple rules are sufficient to be a "regular" or "ordinary" array: no nil values for t[i] for i=1 to N.
You may be better off creating a table with t[i]=0 for i=1 to N where N is larger than anything you expect in that function call (for instance, the largest value in some other table). Once you've completed your insertions, you can set all remaining t[i] which = 0 to nil, but only do that if you are not going to need the table ops.
The other thing you could do is that if you find that an item should be inserted before i, check if t[i-1] is nil; if it is, set it to 0 or -1 or some value that represents "dummy". Repeat this check for i-2 etc.