What's the difference between table.insert(t, i) and t[#t+1] = i?

前端 未结 4 2038
旧巷少年郎
旧巷少年郎 2021-02-05 02:39

In Lua, there seem to be two ways of appending an element to an array:

table.insert(t, i)

and

t[#t+1] = i

Whi

4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-05 03:07

    The following is slightly on the amusing side but possibly with a grain of aesthetics. Even though there are obvious reasons that mytable:operation() is not supplied like mystring:operation(), one can easily roll one's own variant, and get a third notation if desired.

    Table = {}
    Table.__index = table                     
    
    function Table.new()
       local t = {}
       setmetatable(t, Table)
       return t
    end
    
    mytable = Table.new()
    mytable:insert('Hello')
    mytable:insert('World')
    for _, s in ipairs(mytable) do
       print(s)
    end
    

提交回复
热议问题