how to delete all elements in a Lua table?

后端 未结 5 843
长发绾君心
长发绾君心 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:43

    Table elements insert and remove performance compare

    The Table size count 10000000

    [1] while and rawset

    while #t ~= 0 do rawset(t, #t, nil) end
    

    spent time = 0.677220

    [2] next and rawset

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

    spent time = 0.344533

    [3] ipairs and rawset

    for i, v in ipairs(t) do t[i] = nil end
    

    spent time = 0.012450

    [4] for, rawset

    count = #t
    for i=0, count do t[i]=nil end
    

    spent time = 0.009308

    Table elemnets insert

    [1] table insert function

    for i=0, 10000000 do    table.insert(t, i, i) end
    

    spent time = 1.0590489

    [2] use #t

    for i=0, 10000000 do    t[#t+1] = i end
    

    spent time = 0.703731

    [3] for, rawset

    for i=0, 10000000 do rawset(t, i, i) end
    

    spent time = 0.100010

    result.

    Fastest remove : 4

    Fastest insert : 3

提交回复
热议问题