user6010115
user6010115

Reputation:

How to index parent object in Lua?

I'm trying to index a parent object by using its identifier, but it returns nil instead of the object, so it throws a error when executing the script.

local mapit = {
    ...
    ground = function(x, y, w, h, data)
        ...
        local id = 0
        -- mapit is nil in this block
        for i = 0, #mapit.data.ids do
            if id ~= i then
                id = id + 1
            end
        end
        ...
    end,
    data = {
        ids = {}
    }
    ...
}

local myRect = mapit.ground(400, 100, 600, 100)

Upvotes: 1

Views: 191

Answers (1)

Colonel Thirty Two
Colonel Thirty Two

Reputation: 26569

In Lua, locals are not in scope on the right hand of their initializer, so your closure refers to a global named mapit instead.

Declare the local first, then assign to it.

local mapit
mapit = { ... }

Upvotes: 3

Related Questions