簡體   English   中英

Lua中的OOP-創建課程?

[英]OOP in Lua - Creating a class?

我知道在此站點上有一些關於在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的概念很陌生,因此如果這是一個可怕的問題,我感到抱歉。 但是,如果有人可以提供幫助,我將不勝感激。

我以前也遇到過同樣的問題。 您需要兩個表。 一種用於對象方法,一種用於類方法。 將構造對象的元表設置為對象方法表。 例如:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM