Is there anyway to make this work?

Hi,

Apparently this is wrong:

myTable = {} myTable.value = myTable.value + 1  

Is there anyway to make this work? i.e. without initializing the “value” field first and have it initialized at zero by default.

Thanks.

Any value that isn’t initialized is ‘nil’, which means it’s not a math object and cannot be used for math right off the bat. So instead you should do this:

[lua]myTable = {}

myTable.value = (myTable.value or 0) + 1[/lua]

…or you could use a metatable. 

The metatable below will automatically set any uninitialized member to 0.

local myTable = {}; setmetatable(myTable, {     \_\_index = function(t, key)         return 0;     end }) myTable.value = myTable.value + 1   -- returns 1 myTable.value = myTable.value + 1   -- returns 2 myTable.otherValue = myTable.otherValue + 1   -- also returns 1

Fantastic tip, and something that vets forget. 

Any value that isn’t initialized is ‘nil’, which means it’s not a math object and cannot be used for math right off the bat. So instead you should do this:

[lua]myTable = {}

myTable.value = (myTable.value or 0) + 1[/lua]

…or you could use a metatable. 

The metatable below will automatically set any uninitialized member to 0.

local myTable = {}; setmetatable(myTable, {     \_\_index = function(t, key)         return 0;     end }) myTable.value = myTable.value + 1   -- returns 1 myTable.value = myTable.value + 1   -- returns 2 myTable.otherValue = myTable.otherValue + 1   -- also returns 1

Fantastic tip, and something that vets forget.