简体   繁体   English

Lua OOP:表问题

[英]Lua OOP: Problems with tables

There some problems with my OOP. 我的OOP有一些问题。 I have parent with clear table and child with same table. 我的父母有明确的表,孩子有相同的表。 When i'm trying to add object to table of child, object adds to parent's table. 当我尝试将对象添加到子表时,对象添加到父表。

Simple example: 简单的例子:

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)

Result is 1 and 1. But must be 0 and 1. 结果为1和1。但必须为0和1。

How i can isolate child table from parent? 我如何将子表与父表隔离?

In Lua using acc.kit where acc is a table with the metatable Account will first search the key kit from the table acc and then from table Account . 在Lua中,使用acc.kit其中acc是带有元表Account的表)将首先从表acc搜索密钥kit ,然后从表Account搜索密钥kit

In your code acc does not have anything with key kit , so the Account.kit will be accessed. 在您的代码中acc没有任何密钥kit ,因此Account.kit将被访问。

You can solve this simply by defining the kit table for the acc on creation 您可以通过定义用于创建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

Example: https://repl.it/B6P1 示例: https//repl.it/B6P1

I'd recommend using closures to implement OOP: 我建议使用闭包来实现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()

output: 输出:

Fred barked! 弗雷德咆哮!

My name is Fred 我叫弗雷德

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM