Birk
Birk

Reputation: 211

Lua: How to use pcall to see if a loop is crashed

local test = function()
    local a = {
    'test1',
    'test2',
    }
    for i = 1, 3 do
        print(a[i]) -- this will cause an error, because the table only have 2 values
    end
end

if i use test() in a loop is there a way to detect when the loop crash

Upvotes: 1

Views: 199

Answers (1)

Cottient
Cottient

Reputation: 164

The loop wont crash. It will just print nil. Although you can use metatables to see if the loop attempted to index with something that doesn't exist:

local a = {
    'test1',
    'test2',
}

setmetatable(a, {
    __index = function()
       return "Attempt to index with a nil value";
    end
})

for i = 1, 3 do
    print(a[i])
end

Upvotes: 2

Related Questions