Lua 作为参数的self,以及设置范围?
谁能帮我一下吗Lua 作为参数的self,以及设置范围?,lua,Lua,谁能帮我一下吗 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 及 我认为通过将self设
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
及
我认为通过将self设置为param,可以设置范围。为什么在obj2上调用此函数会更新obj1的值?您需要一个函数来创建新对象
-- 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()
您需要一个函数来创建新对象
-- 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()
在您的代码中要求加载一次,第二次要求给您。您应该实现某种复制方法
-- 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
在您的代码中要求加载一次,第二次要求给您。您应该实现某种复制方法
-- 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
我对模块加载的规则有点模糊,但我有70%的把握,您只能“要求”文件一次,因此obj1和obj2只是对同一事物的引用。Source:函数首先查看package.loaded表以确定modname是否已加载。如果是,则require返回存储在package.loaded[modname]中的值。我对模块加载的规则有点模糊,但我有70%的把握,您只能“require”文件一次,因此obj1和obj2只是对同一事物的引用。Source:函数首先查看package.loaded表以确定modname是否已加载。如果是,则require返回存储在package.loaded[modname]中的值。我复制了这一行作为行,它给出了一个异常;尝试调用方法“setPrice”一个nil值我复制了这一行,它给出了一个异常;尝试将方法“setPrice”调用为nil值知道复制方法想要什么吗?知道复制方法想要什么吗?