简体   繁体   中英

Lua OOP: Problems with tables

There some problems with my 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.

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 .

In your code acc does not have anything with key kit , so the Account.kit will be accessed.

You can solve this simply by defining the kit table for the acc on creation

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

I'd recommend using closures to implement 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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