how to delete all elements in a Lua table?

后端 未结 5 844
长发绾君心
长发绾君心 2021-02-04 00:06

How do I delete all elements inside a Lua table? I don\'t want to do:

t = {}
table.insert(t, 1)
t = {}  -- this assigns a new pointer to t

I w

5条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-04 00:56

    For a faster version that ignores the __pairs metamethod:

    local next = next
    local k = next(tab)
    while k ~= nil do
      tab[k] = nil
      k = next(tab, k)
    end
    

    EDIT: As @siffiejoe mentions in the comments, this can be simplified back into a for loop by replacing the pairs call with its default return value for tables: the next method and the table itself. Additionally, to avoid all metamethods, use the rawset method for table index assignment:

    for k in next, tab do rawset(tab, k, nil) end
    

提交回复
热议问题