self as param, and setting scope?

能否有人帮我解决这个问题。

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

  obj1:setPrice(30)
  obj2:setPrice(40)
  print(obj1.price)    -- 这会打印 '40'。在 obj2 上设置价格会更改 obj1 中的价格
end

以及

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

local function _setPrice(self, newprice)
  self.price = newprice
  -- todo 其他的工作
end

M.setPrice = _setPrice

return M

我以为通过将 self 设置为参数,它会设置范围。为什么在 obj2 上调用此函数会更新 obj1 的值?

点赞
用户1847592
用户1847592

你需要一个函数来创建新的对象

-- 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()
2020-02-10 07:53:07
用户7746452
用户7746452

在你的代码中,require 加载一次,第二次 require 会给你相同的对象。你应该实现一些复制方法。

-- 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
2020-02-10 07:54:41