Prototyping an "object" with another "object" in Lua

Viewed 221

Considering the following code:

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

Given that http_extender is meant to be a module that extends http's functionality, a couple of questions:

  1. I have the feeling that there is something inherently wrong with http_extender:new() because it is modifying self for each call, right?
  2. If indeed wrong, what would be the correct way to do it so that each call to http_extender:new() creates a new http "object" that is composed with the functionalities and attributes of http_extender?

Thanks

1 Answers

In order to achieve this I would use something like this

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

The _M:new() method in this code will produce objects with functionality of both _M and the http object.

Related