Lua local function與function區別


1 使用function聲明的函數為全局函數,在被引用時可以不會因為聲明的順序而找不到 
2 使用local function聲明的函數為局部函數,在引用的時候必須要在聲明的函數后面

例子: 
下面這段代碼會報函數找不到的錯誤:lua: test.lua:3: attempt to call global ‘test1’ (a nil value)

function test()
    test2()
    test1()
end

local function test1()
    print("hello test1")
end

function test2()
    print("hello test2")
end

test()

  

改為一下兩種方式就可以正常運行

1 local function的聲明放在引用的前面

local function test1()
    print("hello test1")
end

function test()
    test2()
    test1()
end

function test2()
    print("hello test2")
end

test()

2 local function聲明使用function方式

function test()
    test2()
    test1()
end

function test1()
    print("hello test1")
end

function test2()
    print("hello test2")
end

test()

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM