代码之家  ›  专栏  ›  技术社区  ›  Gabriel

在另一个局部函数中调用局部函数

lua
  •  2
  • Gabriel  · 技术社区  · 6 年前

    local function foo ()
        print('inside foo')
        bar()
    end
    
    local function bar ()
        print('inside bar')
    end
    
    foo()
    

    inside foo
    lua: teste.lua:3: attempt to call global 'bar' (a nil value)
    stack traceback:
            teste.lua:3: in function 'foo'
            teste.lua:10: in main chunk
            [C]: ?
    

    如果我去掉修饰语 local bar 声明,然后按预期工作,输出

    inside foo
    inside bar
    

    酒吧 里面 foo 将两者保持为 地方的 ?

    2 回复  |  直到 6 年前
        1
  •  5
  •   Jack Taylor    6 年前

    你需要定义 bar 之前 foo .

    local function bar ()
        print('inside bar')
    end
    
    local function foo ()
        print('inside foo')
        bar()
    end
    
    foo()
    

    在你的例子中,当你在 函数,那么就Lua而言 酒吧 还不存在。这意味着它默认为值为的全局变量 nil ,这就是为什么会出现错误“尝试调用全局'bar'(nil值)”。

    把它们都作为局部变量,首先需要声明bar变量。

    local bar
    
    local function foo ()
        print('inside foo')
        bar()
    end
    
    function bar ()
        print('inside bar')
    end
    
    foo()
    

    酒吧 是局部变量,可以在末尾添加以下代码:

    if _G.bar ~= nil then
        print("bar is a global variable")
    else
        print("bar is a local variable")
    end
    

    这将检查“bar”是否是 _G ,全局变量表。

        2
  •  2
  •   Tom Blodget    6 年前

    local function foo () end
    

    相当于

    local foo  
    foo = function() end  
    

    在Lua中,函数是一级值。因此,在定义之前它是不可用的。