首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Lua -创建一个类?

在Lua -创建一个类?
EN

Stack Overflow用户
提问于 2016-08-06 15:31:14
回答 1查看 1.2K关注 0票数 2

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

我正在尝试创建一个名为" human“的类,并使其成为使用"human”的“新”构造函数创建的对象,继承除它的构造函数之外的所有人类内部的一切。但是,我也不想在人类内部,在人类身上使用方法。所以人类类中的任何东西,都只传递给被创建的对象。下面是一个例子:

代码语言:javascript
复制
-- "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的概念非常陌生,所以如果这是一个可怕的问题,我很抱歉。但如果有人能帮忙,我会很感激的。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-08-06 15:55:27

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

代码语言:javascript
复制
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

并使用它

代码语言:javascript
复制
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
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38805890

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档