lua-users home
lua-l archive

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


On 19 January 2018 at 21:26, Elias Hogstvedt <eliashogstvedt@gmail.com> wrote:

So to solve this I would simply add an array type to Lua which would help distinguish between tables and arrays. To distinguish our new array type from arrays in other languages that start from 0 and can only contain a certain type of value we can just call it a "list" instead.


An attempt at something that won't break existing code. It wouldn’t require *very* much new code, and it wouldn't affect us who are used to creating real sequences. But people really want holes in their sequences...

t = { "a", "b", nil, nil, "e", "f" }
table.makesequence(t, 6) -- equivalent to t._SEQ = 6
-- now table functions respect the _SEQ field if (and only if) it is present
for i, v in ipairs(t) print(v) end -- a b nil nil e f
t:makesequence(8)
for i, v in ipairs(t) print(v) end -- a b nil nil e f nil nil
t:insert(5, "X") -- table.insert increments _SEQ, table.remove decrements it
for i, v in ipairs(t) print(v) end -- a b nil nil X e f nil nil
print(#t) -- 9 (__len first checks _SEQ)
t:makesequence("max") -- sets t._SEQ to maximum positive integer, in this case 7
print(t:concat(" ")) -- a b   X e f
t._NILCONCAT = "nil" -- default is ""
print(t:concat(" ")) -- a b nil nil X e f
t[11] = "k" -- _SEQ doesn't change, use table.insert
t:makesequence(false) -- equivalent to t.SEQ = nil
t:makesequence(3, true) -- optional second argument. If set, erases everything higher than _SEQ
for i, v in ipairs(t) print(v) end -- a b nil
for k, v in pairs(t) print(k .. "," .. v) end -- 1,a 2,b _SEQ,3 _NILCONCAT,nil

Vaughan