Lua 初學者隨筆 一


 

1. 關於return

function test(a, b)
    print("Hello")
    return 
    print("World")
end

--call the function
test(1, 2);

--[[output
Hello 
World
]]

奇怪之處:

①Lua關於return語句放置的位置:return用來從函數返回結果,當一個函數自然結束結尾會的一個默認的return。Lua語法要求return只能出現在block的結尾一句(也就是說:任務chunk的最后一句,或者在end之前,或者else前,或until前),但是在本程序中竟然沒有報錯

②當執行return后,函數應該返回了,也就是說,上述程序本應該只輸出Hello,然后函數就應當結束,不會再輸出world,但是本程序確實Hello和world都輸出了。

③若是return后面緊跟一個返回值,該程序就正常報錯了,符合了Lua語法要求return只能出現在block的結尾一句。

function test(a, b)
 print("Hello")
 return 1
 print("World")
end

--call the function
test(1, 2);
--[[error: 
lua: hello.lua:4: 'end' expected (to close 'function' at line 1) near 'print'
]]

2. 關於返回不定參數

function newtable(...)
return(...) -- error
end
tb1=newtable("a","v","c")
for i=1,#tb1 do 
print (i,tb1[i])
end 

return(...) 由於加了括號,只能返回第一個值,其它的值被忽略了
正確的做法是:return{...}

3.select函數

function printargs(...)
local num_args=select("#", ...)
    for i=1 ,num_args do 
        local arg=select(i, ...)
        print (i,arg)
   end
end
printargs("a","b",3,"d")

select (index, ···)

If index is a number, returns all arguments after argument number index. Otherwise, index must be the string "#", and select returns the total number of extra arguments it received.

 

4.


免責聲明!

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



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