lua - 在 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 功能的模块,有几个问题:
- 我觉得有一些内在的问题,
http_extender:new()
因为它正在self
为每次调用进行修改,对吗? - 如果确实是错误的,那么正确的方法是什么,以便每次调用都
http_extender:new()
创建一个http
由 的功能和属性组成的新“对象”http_extender
?
谢谢
解决方案
为了实现这一点,我会使用这样的东西
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 对象功能的对象。
推荐阅读
- java - 如何让我的 React Native 应用出现在 android 的分享列表中
- python - 如何从字符串中给出数据框名称,而不是通过硬编码
- java - 如何在 Java 中过滤带有度量的单词
- asp.net-mvc - 如果我在索引视图中放入表格的最后一列,为什么标签不起作用?
- javascript - 获取数据并显示在弹出组件上
- javascript - 在 HTML 上使用 JS 创建带有 href 的动态列表
- php - 虽然我的 wamp 服务器安装在 C: 驱动器中并且我正在我的 I: 驱动器中安装我的 laravel 项目这是成功部署我的项目的权利吗
- javascript - 如果特定单词出现在编辑器中,则更改它们的颜色
- 3d - 如何静态换行
- reactjs - react-scrollbars-custom:路由时固定位置无法正常工作