【问题标题】:How to get out a variable from a function?如何从函数中取出变量?
【发布时间】:2014-08-14 21:48:39
【问题描述】:

所以,我正在尝试从函数中获取变量。我有一个 Garry's Mod 脚本,其中包含以下语句:

http.Fetch("http://google.fr",  function(body)
    return body
end)

我的问题是:如何从中检索我的身体变量?我认为没有“全局”关键字(例如在 PHP 中)或 Lua 中的引用之类的东西。 谢谢!

【问题讨论】:

  • 如果你有一个返回变量的函数,那么local result = foo()...
  • 你传递的回调直到页面被抓取后才会被调用,这将在调用http.Fetch的函数返回之后。
  • @TheParamagneticCroissant 我不完全理解,我无法让它以这种方式工作。
  • @ColonelThirtyTwo 你是对的,所以我的代码应该在回调函数之间,所以如果页面没有加载,我就不能使用正文值。但是还有办法从中检索变量吗?

标签: lua garrys-mod


【解决方案1】:

您处理此问题的最简单方法是编写一个函数,将body 结果物理加载到您使用的任何接口,或者在 Fetch 调用中添加代码以自行加载。像这样的:

-- just an example of some function that knew how to load a body result 
-- in your context
function setBody(body) 
    someapi.Display(body)
end

http.Fetch('http://someurl.com', 
    function(body) 
        -- you have access to outer functions from this scope. if you have
        -- some function or method for loading the response, invoke it here
        setBody(body)
        -- or just someapi.Display(body)
    end
)

我认为您感到困惑,因为您似乎更多地处于功能设计思维方式中,而您现在正在混合使用事件驱动设计。在事件驱动设计中,您基本上是使用参数调用函数并给它们一个函数回调,其中包含一些您希望在调用的函数完成后最终运行的代码。

另外,在 Lua 中有 一个全局关键字 - 你有全局表 _G。您可能会设置_G.body = body,但我会避免这种情况并传递回调函数,这些函数知道一旦调用它们就知道如何加载。

【讨论】:

  • 谢谢,我确实很困惑。我在常用的 PHP 中不使用回调函数。
【解决方案2】:

如果不能简单地从函数返回值,可以通过upvalue进行更新,函数执行后即可使用:

local bodycopy
http.Fetch("http://google.fr",  function(body)
    bodycopy = body
end)
-- assuming http.Fetch block here until the content of the URL is retrieved...
print(bodycopy)

【讨论】:

  • 谢谢!我不知道,它会很有用。
【解决方案3】:

我认为在 Lua 中没有“全局”关键字(例如在 PHP 中)或引用之类的东西。

closures,它可以让您访问在子函数中定义为local 的变量。

例如:

function makeCounter()
    local i = 0
    local function counterfunc()
        i = i + 1
        return i
    end
    return coutnerfunc
end

local counter1 = makeCounter()
print(counter1()) -- 1
print(counter1()) -- 2
print(counter1()) -- 3

local counter2 = makeCounter()
print(counter2()) -- 1
print(counter2()) -- 2

print(counter1()) -- 4

这意味着您可以存储对象以在回调函数中使用。

function ENT:GetPage()
    -- The implicitly-defined self variable...
    http.Fetch("www.example.com", function(body)
        -- ...is still available here.
        self.results = body
    end)
end

注意http.Fetch是一个异步函数;它稍后在实际获取页面时调用回调。这行不通:

function ENT:GetPage()
    local results
    http.Fetch("www.example.com", function(body)
        results = body
    end)
    return results -- The closure hasn't been called yet, so this is still nil.
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-18
    相关资源
    最近更新 更多