在 Lua 中使用另一个“对象”原型进行原型设计

考虑以下代码:

http.lua

local function create_socket()
    -- 做一些创建套接字的操作
    return socket, err
end

local _M
local mt = { __index = _M }

function _M:new()
    local sock, err = create_socket()
    if not sock then
        return nil, err
    end
    return setmetatable({ sock = sock, keepalive = true }, mt)
end

function _M:function1() end
function _M:function2() end

return _M

http_extender.lua

local http = require "http"

local _M = {}

function _M:new()
    local o = setmetatable(self, {__index = http.new()})
    return setmetatable({}, {__index = o})
end

function _M:function3() end
function _M:function4() end

return _M

考虑到http_extender是一个扩展http功能的模块,有几个问题:

1.我有一种感觉,即http_extender:new()有一些与众不同之处,因为它为每个调用进行了修改,是吗? 2.如果确实有问题,正确的方法是什么,以便每次调用http_extender:new()都创建一个具有http_extender功能和属性的新`http“object”?

谢谢

点赞
用户11731719
用户11731719

为了实现这个目标,我会使用类似以下的代码:

local http = require "http"

local _M = {}

function _M:new()

    local newob = http.new()

    local mt = getmetatable( newob )
    setmetatable( mt.__index, { __index = self } )

    return newob

end

function _M:function3() end
function _M:function4() end

return _M

这段代码中的_M:new()方法将生成同时具有_Mhttp对象功能的对象。

2020-04-08 00:49:19