Joe Huang
Joe Huang

Reputation: 6550

How to use a value in a table inside itself (Lua language)?

I have a lua table like this:

local defaultSize = 14
local field = {
    sizeA = defaultSize,
    sizeB = sizeA,
}

My intention is to set sizeB to the value of field.sizeA, however the code above does not work. field.sizeB is nil in this case.

How to set sizeB to whatever sizeA is inside the table definition directly?

Upvotes: 1

Views: 374

Answers (1)

Oliver
Oliver

Reputation: 29453

You could have an init function in table and call that:

local defaultSize = 14
local field = {
    init = function (self, size) 
        self.sizeA = size or defaultSize -- size only if given, otherwise defaultSize
        self.sizeB = self.sizeA
    end
}

field:init() -- implicit "self" arg is "field", defaultSize will be used
field:init(16) -- size will be 16 rather than 14
print(field.sizeB) -- prints 14

This has the clear advantage of aggregating all initialization of table instance in one place, you can have conditionals etc once your logic gets more complex. You don't have to have init() as member of table, but it is always a good idea to keep dependencies obvious and close together.

Upvotes: 1

Related Questions