首页 > 解决方案 > 在 Lua 中用另一个“对象”制作一个“对象”的原型

问题描述

考虑以下代码:

http.lua

local function create_socket()
    -- do stuff to 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's 功能的模块,有几个问题:

  1. 我觉得有一些内在的问题,http_extender:new()因为它正在self为每次调用进行修改,对吗?
  2. 如果确实是错误的,那么正确的方法是什么,以便每次调用都http_extender:new()创建一个http由 的功能和属性组成的新“对象” http_extender

谢谢

标签: lua

解决方案


为了实现这一点,我会使用这样的东西

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()方法将生成具有 _M 和 http 对象功能的对象。


推荐阅读