在Lua中创建一个对象的引用而不使用“:”。
我的目标是为Lua编写的GUI编写一个插件。它应该在不改变GUI本身的代码的情况下替换创建窗口的过程。创建窗口的原始函数如下:
function GUIclass.createWindow(arg1, arg2, arg3, arg4, arg5)
-- do stuff
return window
end
我的方法如下:
function MyClass.createWindow(arg1, arg2, arg3, arg4, arg5)
local foo = self.attributeOne -- 无效,因为self未定义
-- do some more stuff wich requires foo
return window
end
... 稍后
MyClassInst = MyClass:new()
请注意,这两个函数位于不同的文件中。我想法是在初始化后替换指向旧函数的指针
GUIclass.createWindow = MyClass.createWindow
除了在 MyClass.createWindow 中似乎无法获取 MyClass 实例的引用之外,一切都很正常。我尝试使用
local self = MyClassInst
在 MyClass.createWindow 中,但它是 nil。我也不喜欢这个方法,因为它仅限于类的一个实例。如标题所述,":" 也不起作用,因为该函数是通过 "GUIclass.createWindow(args)" 调用的(现在指向 MyClass.createWindow)。
那么,如何在不使用 ":" 的情况下引用类的实例?
你大多数情况下是不能这样做的,这正是 : 在这里为你做的事情。
如果你使用 . 调用函数,除了给定的参数(以及该函数闭包机制中的变量),你就没有任何调用上下文。
如果你想创建多个自定义的 createWindow 函数,你可以让它们闭合一些类实例变量并在内部使用它,但你必须手动完成,并且在其之前必须先有这些类可用。我不知道这是否适用于你的情况。
我也不明白代码中存在的问题。
你是否希望有多个自定义的 createWindow 函数适当地猴子补丁到 GUIclass 中?或者为什么你需要让 createWindow 按照你编写的方式带有 self 参数?
如果您正在创建一个新的窗口对象,则无需使用自身参数。相反,可以在MyClass.createWindow函数中创建新实例。可以通过使用表构造器({})或调用另一个构造函数来实现。例如:
local oldCreateWindow = GUIclass.createWindow
function MyClass.createWindow(...)
local window = oldCreateWindow(...)
local foo = window.attributeOne
-- do some more stuff wich requires foo
return window
end
我认为我现在更好地理解了您的问题。我相信使用闭包比使用类更好。
-- MyClass实际上只是一个具有许多属性的表格,这些属性经常更改。
local MyClass = {}
local function createWindow(arg1, arg2, arg3, arg4, arg5)
local foo = MyClass.attributeOne
-- do some more stuff wich requires foo
return window
end
GUIclass.createWindow = createWindow
在此之后,您对MyClass所做的任何更改都应该对GUIclass.createWindow可见。
- 如何将两个不同的lua文件合成一个 东西有点长 大佬请耐心看完 我是小白研究几天了都没搞定
- 如何在roblox studio中1:1导入真实世界的地形?
- 求解,lua_resume的第二次调用继续执行协程问题。
- 【上海普陀区】内向猫网络招募【Skynet游戏框架Lua后端程序员】
- SF爱好求教:如何用lua实现游戏内调用数据库函数实现账号密码注册?
- Lua实现网站后台开发
- LUA错误显式返回,社区常见的规约是怎么样的
- lua5.3下载库失败
- 请问如何实现文本框内容和某个网页搜索框内容连接,并把网页输出来的结果反馈到另外一个文本框上
- lua lanes多线程使用
- 一个kv数据库
- openresty 有没有比较轻量的 docker 镜像
- 想问一下,有大佬用过luacurl吗
- 在Lua执行过程中使用Load函数出现问题
- 为什么 neovim 里没有显示一些特殊字符?
- Lua比较两个表的值(不考虑键的顺序)
- 有个lua简单的项目,外包,有意者加微信 liuheng600456详谈,最好在成都
- 如何在 Visual Studio 2022 中运行 Lua 代码?
- addEventListener 返回 nil Lua
- Lua中获取用户配置主目录的跨平台方法
我就当作一个答案发表吧。。
尝试:
function MyClass.createWindow(self, arg1, arg2, arg3, arg4, arg5)根据我从lua记得的,相等于:
function MyClass:createWindow(arg1, arg2, arg3, arg4, arg5)就像
class:something()等于