自我作為參數,並設置範圍? (self as param, and setting scope?)


問題描述

自我作為參數,並設置範圍? (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 ausgeorgeEgor SkriptunoffLeszek Mazur)

參考文件

  1. self as param, and setting scope? (CC BY‑SA 2.5/3.0/4.0)

#lua






相關問題

使用 MSXML2.ServerXMLHTTP 從網頁訪問數據會在 Lua 中返回截斷的數據 (Using MSXML2.ServerXMLHTTP to access data from a web page returns truncated data in Lua)

如何在 VS 2008 中包含 Lua 庫 (How can I include Lua library in VS 2008)

Corona 中的 iPad 式慣性滾動 (iPad-style inertial scrolling in Corona)

Lua cư xử kỳ lạ trên nền tảng PowerPC / LynxOS, tại sao? (Lua behaves weird on PowerPC/LynxOS platform, why?)

我們如何在函數輸入參數中輸入類型值作為對象? (How do we input type value as object in function input parameter?)

反編譯 Lua 字節碼的最佳工具? (Best tool(s) for decompiling Lua bytecode?)

本機 Lua 中的高效可變字節數組 (Efficient mutable byte array in native Lua)

在 Lua 中字符串化對象名稱 (Stringify object name in Lua)

純 Lua 中的全功能正則表達式庫 (Fully-featured regex library in pure Lua)

自我作為參數,並設置範圍? (self as param, and setting scope?)

已經放 } 但錯誤仍然說 } 是預期的? (Already put } but the error still says that } is expected?)

我想使用 HPC 的 gpu 並嘗試 module add CUDA ...但出現錯誤。錯誤是“Lmod 檢測到以下錯誤: (I want to use the gpu of the HPC and try module add CUDA... But errors occurs. The error is "Lmod has detected the following error:)







留言討論