Pan Rusher
Pan Rusher

Reputation: 11

Lua set table elements in table function

Here is the snippet:

    local t = {}

    t.tt = {}

    function t.xx()
        for i=1,10 do
            t.tt[i] = i
        end
    end


    for i=1,10 do
        print(t.tt[i])
    end

Result of print function is all nil.Why all elements in t.tt is nil ?

Upvotes: 0

Views: 293

Answers (1)

CaringDev
CaringDev

Reputation: 8551

You need to actually run the function before printing:

local t = {}

t.tt = {}

function t.xx()
    for i=1,10 do
        t.tt[i] = i
    end
end

-- execute function here
t.xx()

for i=1,10 do
    print(t.tt[i])
end

or just assign the values:

local t = {}

t.tt = {}

-- no function here
for i=1,10 do
    t.tt[i] = i
end

for i=1,10 do
    print(t.tt[i])
end

Upvotes: 7

Related Questions