I'm working on a game in Corona/Lua, and implementing a class called "Item" which represents an in game weapon, armor, amulet, etc. And I'm new to object-oriented Lua.
After creating a new instance of the class, I'm finding that setting certain properties of the object seems to set them in the class metatable, not in the object itself.
Here is the class and constructor:
local Item = {
name = nil,
itemType = nil,
scarcity = "basic",
baseDamage = 0, -- Bow only
bonuses = {
damageBonus = 0,
speedBonus = 0,
critBonus = 0,
dropBonus = 0,
rechargeBonus = 0,
xpBonus = 0
}
}
-- Creates a simple blank instance of the Item class.
function Item:new(o)
local item = o or {}
setmetatable(item, self)
self.__index = self
return item
end
Now let's say I create two objects based on this prototype:
local bow = Item:new()
bow.itemType = "bow"
starterBow.baseDamage = 5
local ring = Item:new()
ring.itemType = "ring"
ring.bonuses.damageBonus = 0.25
To my dismay, the "bonuses.damageBonus" property seems to be getting set inside the metatable and therefore applying to every item (i.e. the bow also gets the damage bonus, and stacking with the ring). However the behavior seems limited to the "bonus" properties. If I set the "itemType" property, it is attached to the object, not the class, as expected.
The behavior I'd like to see is that the fields of the "bonuses" table can be set for individual items. Any idea what I'm doing wrong? Thanks!