在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)。

那么,如何在不使用 ":" 的情况下引用类的实例?

点赞
用户1009655
用户1009655

我就当作一个答案发表吧。。

尝试:

function MyClass.createWindow(self, arg1, arg2, arg3, arg4, arg5)

根据我从lua记得的,相等于:

function MyClass:createWindow(arg1, arg2, arg3, arg4, arg5)

就像

class:something()

等于

class.something(class)
2014-05-06 13:54:38
用户258523
用户258523

你大多数情况下是不能这样做的,这正是 : 在这里为你做的事情。

如果你使用 . 调用函数,除了给定的参数(以及该函数闭包机制中的变量),你就没有任何调用上下文。

如果你想创建多个自定义的 createWindow 函数,你可以让它们闭合一些类实例变量并在内部使用它,但你必须手动完成,并且在其之前必须先有这些类可用。我不知道这是否适用于你的情况。

我也不明白代码中存在的问题。

你是否希望有多个自定义的 createWindow 函数适当地猴子补丁到 GUIclass 中?或者为什么你需要让 createWindow 按照你编写的方式带有 self 参数?

2014-05-06 13:58:54
用户3574628
用户3574628

如果您正在创建一个新的窗口对象,则无需使用自身参数。相反,可以在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可见。

2014-05-06 17:46:13