Lua OOP:表的问题

时间:2015-12-05 12:24:39

标签: oop lua

我的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。

我如何将父表与父母隔离?

2 个答案:

答案 0 :(得分:0)

在Lua中使用acc.kit其中acc是包含元组Account的表格,首先会从表格kit中搜索密钥acc然后从表格中搜索Account

在您的代码acc中没有关键kit的任何内容,因此将访问Account.kit

您只需通过定义创建时的套件表

即可解决此问题
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

答案 1 :(得分:0)

我建议使用闭包来实现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()

输出:

弗雷德咆哮着!

我的名字是弗雷德