簡體   English   中英

Lua OOP:表問題

[英]Lua OOP: Problems with tables

我的OOP有一些問題。 我的父母有明確的表,孩子有相同的表。 當我嘗試將對象添加到子表時,對象添加到父表。

簡單的例子:

Account = {}
Account.__index = Account
Account.kit = {}

function Account.create(balance)
   local acnt = {}             -- our new object
   setmetatable(acnt,Account)  -- make Account handle lookup
   acnt.balance = balance      -- initialize our object
   return acnt
end

function Account:withdraw(amount)
   self.balance = self.balance - amount
end

-- create and use an Account
acc = Account.create(1000)
acc:withdraw(100)


table.insert(acc.kit, "1")

print(#Account.kit)
print(#acc.kit)

結果為1和1。但必須為0和1。

我如何將子表與父表隔離?

在Lua中,使用acc.kit其中acc是帶有元表Account的表)將首先從表acc搜索密鑰kit ,然后從表Account搜索密鑰kit

在您的代碼中acc沒有任何密鑰kit ,因此Account.kit將被訪問。

您可以通過定義用於創建acc的套件表來解決此問題

Account = {}
Account.__index = Account
Account.kit = {} -- You can now remove this if you do not use it - I preserved it to make the test prints to still work.

function Account.create(balance)
   local acnt = {}             -- our new object
   setmetatable(acnt,Account)  -- make Account handle lookup
   acnt.balance = balance      -- initialize our object
   acnt.kit = {}               -- define kit to be a subtable
   return acnt
end

示例: https//repl.it/B6P1

我建議使用閉包來實現OOP:

local Animal = {}

function Animal.new(name)

  local self = {}
  self.name = name

  function self.PrintName()
    print("My name is " .. self.name)
  end

  return self

end

--now a class dog that will inherit from animal
local Dog = {}

function Dog.new(name)

  -- to inherit from Animal, we create an instance of it
  local self = Animal.new(name)

  function self.Bark()
    print(self.name .. " barked!")
  end

  return self

end


local fred = Dog.new("Fred")
fred.Bark()
fred.PrintName()

輸出:

弗雷德咆哮!

我叫弗雷德

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM