ausgeorge
ausgeorge

Reputation: 1015

self as param, and setting scope?

Can someone please help me with this.

local function TestPrice()
  local obj1 = require("myObj")
  local obj2 = require("myObj")

  obj1:setPrice(30)
  obj2:setPrice(40)
  print(obj1.price)    -- this prints '40'. Setting price on obj2 changes the price in obj1
end

and

-- myObj.lua
local M = {
price = -1;}

local function _setPrice(self, newprice)
  self.price = newprice
  -- todo other stuff
end

M.setPrice = _setPrice

return M

I thought that by setting self as a param it set the scope. Why does calling this function on obj2 update the value of obj1?

Upvotes: 1

Views: 95

Answers (2)

Leszek Mazur
Leszek Mazur

Reputation: 2531

In your code require load once, and second require give you same object. You should implement some kind of copy method.

-- myObj.lua
local M = {
price = -1;}

local function _setPrice(self, newprice)
  self.price = newprice
  -- todo other stuff
end

function M:copy()
  return {["price"] = self.price, ["setPrice"]=_setPrice, ["copy"] = self.copy}
end

M.setPrice = _setPrice

return M

Upvotes: 1

Egor Skriptunoff
Egor Skriptunoff

Reputation: 23737

You need a function to create new object

-- myObj.lua
local M = {}

local function _setPrice(self, newprice)
  self.price = newprice
  -- todo other stuff
end

M.setPrice = _setPrice
M.__index = M

local function create_new_obj()
   local obj = {price = -1}
   setmetatable(obj, M)
   return obj
end

return create_new_obj


-- main.lua
local function TestPrice()
  local obj1 = require("myObj")()
  local obj2 = require("myObj")()

  obj1:setPrice(30)
  obj2:setPrice(40)
  print(obj1.price, obj2.price)
end

TestPrice()

Upvotes: 2

Related Questions