【问题标题】:OOP in Lua - Creating a class?Lua 中的 OOP - 创建一个类?
【发布时间】:2016-08-06 15:31:14
【问题描述】:

我知道在这个网站上有一些关于在 Lua 中实现 OOP 的问题,但是,这个有点不同(至少与我发现的相比)。

我正在尝试创建一个名为“human”的类,并使其使用“human”的“new”构造函数创建的对象继承human 内部的所有内容,除了它的构造函数。但是,我也不希望能够在人类内部,在人类身上使用方法。因此,人类类中的任何内容都只会传递给创建的对象。这是一个例子:

-- "Human" class
human = {}

function human.new(name)
    local new = {} -- New object

    -- Metatable associated with the new object
    local newMeta = 
    {
        __index = function(t, k)
            local v = human[k] -- Get the value from human
            print("Key: ", k)
            if type(v) == "function" then -- Takes care of methods
                return function(_, ...) 
                    return v(new, ...) 
                end
            else
                return v -- Otherwise return the value as it is
            end
        end
    }

    -- Defaults
    new.Name = name
    new.Age = 1

    return setmetatable(new, newMeta)
end

-- Methods
function human:printName()
    print(self.Name)
end

function human:setAge(new)
    self.Age = new
end

-- Create new human called "bob"
-- This works as expected
local bob = human.new("Bob")
print(bob.Name) -- prints 'Bob'
bob:printName() -- prints 'Bob'
bob:setAge(10) -- sets the age to 10
print(bob.Age) -- prints '10'

-- But I don't want something like this allowed:
local other = bob.new("Mike") -- I don't want the constructor passed

-- I'd also like to prevent this from being allowed, for "human" is a class, not an object.
human:printName()

所以用human.new("Bob") 创建对象工作正常,但它也传递了构造函数,我仍然可以在类上使用对象方法。我对 OOP 的概念很陌生,所以如果这是一个可怕的问题,我很抱歉。但如果有人能提供帮助,我将不胜感激。

【问题讨论】:

  • 查看base,如果您正在为这类事情寻找一个好的基础。 source code 是不言自明的,可能会提供一些见解。

标签: oop lua


【解决方案1】:

我之前也遇到过同样的问题。你需要两张桌子。一种用于对象方法,一种用于类方法。将构造对象的元表设置为对象方法表。例如:

local Class = {}
local Object = {}
Object.__index = Object

function Class.new()
    return setmetatable({}, Object)
end
setmetatable(Class, {__call = Class.new})

function Object.do()
    ...
end

return Class

并使用它

Class = require('Class')

local obj = Class.new() -- this is valid
obj.do()                -- this is valid
obj.new()               -- this is invalid
Class.do()              -- this is invalid

【讨论】:

  • 非常感谢,感谢您的宝贵时间。
猜你喜欢
  • 2021-09-21
  • 2016-05-19
  • 2020-07-29
  • 2012-02-04
  • 2022-07-21
  • 2022-01-25
  • 2012-03-04
  • 2017-10-22
  • 2016-03-27
相关资源
最近更新 更多