問題描述
自我作為參數,並設置範圍? (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) ‑‑ this prints '40'. Setting price on obj2 changes the price in obj1
end
和
‑‑ myObj.lua
local M = {
price = ‑1;}
local function _setPrice(self, newprice)
self.price = newprice
‑‑ todo other stuff
end
M.setPrice = _setPrice
return M
我認為通過將 self 設置為參數來設置範圍。為什麼在obj2上調用這個函數會更新obj1的值?
參考解法
方法 1:
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()
方法 2:
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
(by ausgeorge、Egor Skriptunoff、Leszek Mazur)