lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]



On 3 Aug 2007 Stefan Brantschen wrote:

How does one generalize that to insert a value anywhere in a varargs?
rewrite table.insert in Lua, so it will use xxx.n, not #n. something
like:

local function NewInsert (tbl, position, value)
  if position <= tbl.n then
    for f = tbl.n, position, -1 do tbl[f+1] = tbl[f]; end;
  end;
  tbl[position] = value;
  return tbl;
end;

I'd simply use (t.n is the number of elements in the table):

local function new_insert(t, val, pos)
  pos = pos or t.n + 1
  table.insert(t, pos, val)
  t.n = t.n + 1
  return t
end

Rubbish. Sorry. I /really/ thought (based on some testing) table.insert handles tables with nils in case you explicitly indicate the insert position, but it does not. (And yes, t.n = t.n + 1 is also wrong, table.maxn might do the trick.) Ouch. Not my day.