Adding objects to array on Lua

Viewed 132

First of all I'm new on lua, I'm trying to implement a simple shopping cart as an object oriented exercise.

So I defined a Cart Object which stores several items objects

Cart = {
    items = {},
    discount = 0
}

function Cart:new(discount)
    local object = {}
    setmetatable(object, {__index = self})
    self.discount = discount

    return object
end

function Cart:addItem(item)
    table.insert(self.items, item)
end

function Cart:GetTotal()
    local total = 0
    for i = 1, #self.items do
        total = total + self.items[i]:GetPrice()
    end
    return total - self.discount
end

Each Item has the responsibility of calculate their price:

Item = {
    units = 0,
    pricePerUnit = 5,
    name = ""
}

function Item:new(units, pricePerUnit, name)
    local object = {}
    setmetatable(object, {__index =  self})
    self.units = units
    self.pricePerUnit = pricePerUnit
    self.name = name

    return object
end

function Item:GetPrice()
    return self.units * self.pricePerUnit
end

But when I create the object and add items I get 60 as result, When I debugged the script I found that all the elements of the table are identical as if they were overwritten, could someone explain to me why and how can it be solved? Thanks in advance.

local shoppingCart = Cart:new(0)
shoppingCart:addItem(Item:new(1, 10, "Oranges"))
shoppingCart:addItem(Item:new(1, 15, "lemons"))
shoppingCart:addItem(Item:new(1, 20, "Strawberries"))

print(shoppingCart:GetTotal())
1 Answers

Cart:new and Item:new are meant to create new objects, therefore you call them on the classes themselves rather than on instances. That means the self that gets passed to those methods is those classes.

In both of those methods, you create an object table to become the new object, so you need to set the fields on that object, instead of modifying the class, eg, object.discount = discount.

Related