我发现了一个关于后挂钩的话题,但我认为这与我想要完成的事情不一样。 topic i found
我需要的是以下内容:
local someBoolean = false
function doSomething() -- this is the function used in __index in a proxy table
someBoolean = true
return aFunction -- this is function that we can NOT alter
end
我需要能够在返回后运行代码“someBoolean = false”...(是的,我知道这不应该发生:p)考虑到aFunction本身可能包含其他函数,我希望someBoolean为true对于aFunction的整个范围,但在此之后,它必须被转回假
如果我不能很好地解释它,我很抱歉。复制粘贴我实际项目的相关代码会太大,我不想浪费你的时间。 我现在已经坚持了一段时间,而我似乎无法弄明白......
(编辑:我不能在函数之后放置someBoolean = false,因为该函数实际上是代理表上的__index函数)
编辑:相关的一段代码。我希望它有点清楚
local function objectProxyDelegate(t, key)
if not done then -- done = true when our object is fully initialised
return cls[key] -- cls is the class, newinst is the new instance (duh...)
end
print("trying to delegate " .. key)
if accessTable.public[key] then
print(key .. " passed the test")
objectScope = true
if accessTable.static[key] then -- static function. return the static one
return cls[key] -- we need to somehow set objectScope back to false after this, otherwise we'll keep overriding protected/private functions
else
return newinst[key]
end
elseif objectScope then
print("overridden protected/private")
return cls[key]
end
if accessTable.private[key] then
error ("This function is not visible. (private)", 2)
elseif accessTable.protected[key] then
error ("This function is not visible to an instance. (protected)", 2)
else
error ("The function " .. key .. " doesn't exiist in " .. newinst:getType(), 2) -- den deze...
end
end
答案 0 :(得分:1)
由于您需要返回一个函数(而不是评估一个函数),您可以为aFunction
创建一个代理并返回该代理。以下是它的工作原理(Nicol Bolas从解决方案中获取了大量代码):
local someBoolean = false
function doSomething(...) -- this is the function used in __index in a proxy table
someBoolean = true
-- Return a proxy function instead of aFunction
return function(...)
local rets = { aFunction(...) }
someBoolean = false
return table.unpack(rets)
end
end
答案 1 :(得分:0)
return
语句后,您无法执行代码。正确的答案是调用函数,捕获返回值,设置变量,然后返回返回值。例如:
local someBoolean = false
function doSomething(...) -- this is the function used in __index in a proxy table
someBoolean = true
local rets = { aFunction(...) } -- this is function that we can NOT alter
someBoolean = false
return table.unpack(rets)
end