How to initialize table size in lua

3.1k views Asked by At

What is the most efficient way to convert number to table? Or is it possible to make a table without loops?

local t = 10 -- given number
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} -- result

Update: the t variable is mutable number and I want to for each the value.

t = 3

function foreach(f, t)
  for i, v in ipairs(t) do
    f(v)
  end   
end

foreach(print, t)
1
2
3

I need a just the quickest way of new Array(n) in Lua. Or doesn't make any sense?

2

There are 2 answers

0
Tom Blodget On BEST ANSWER

Maybe you don't know how to answer @Sebastian's question. Here are a few alternatives to get you thinking.

Since your table has only computed elements, you could omit the storage and just perform the calculation on every read access (index operation).

local function newArray(size)
    local t = {}
    setmetatable(t, {
           __index = function (_, i) 
               return i >= 1 and i <= size and i or nil end})
    return t
end

t10 = newArray(10)
for i = 0, 11 do -- ipairs won't work as expected with such a table
    print(i, t10[i])
end
t10[2] = "stored values override __index"
print(t10[2])

Of course, you could also replace the table with just an identity function that returns the value, or even just an identity expression. But, maybe you have an unexpressed requirement for a table or you need ipairs to iterate over the sequence.

Speaking of iterators,

local function seq_itor(first, last)
    local i = first - 1
    return function ()
        i = i + 1
        if i <= last then return i end
    end
end

for i in seq_itor(1, 10) do
    print(i)
end
0
Jasmijn On

The simplest way to do that would be to define a function:

function newArray(size)
    local t = {}
    for i = 1, size do
        t[i] = i
    end
    return t
end