简体   繁体   中英

Lua: Scope of local functions

I'm a little confused regarding local functions in Lua. Please have a look at this following, simplified example.

function test()
  local function f()
    print("f")
    g()
  end

  local function g()
    print("g")
  end

  f()
end

test()

Upon running this code, I get an error in function "f", because function "g" is a nil value. From my understanding, both functions should have been declared once the code reaches the call to function "g", and since both functions have not yet reached the end of the block they're in (function "test"), they should still be accessible. This code works fine when declaring the functions as global, and I'm really not sure why it doesn't work with local functions. The book "Programming in Lua" didn't help me either.

local function g() <BODY> end is equivalent local g; g=function () <BODY> end local g; g=function () <BODY> end .

In f , the name g is resolved a global because the local g appears after f has ended. This is what the error message tells us:

attempt to call a nil value (global 'g')

Try defining g before f .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM