- Lua Quick Start Guide
- Gabor Szauer
- 211字
- 2021-08-05 10:30:40
Any number of arguments
Unlike other programming languages, in Lua you don't have to provide the same number of arguments as a function's declaration has. For example, adding more arguments than is declared will simply ignore the extra arguments:
-- Declare the function, takes two arguments
function AddAndPrint(x, y)
local result = x + y;
print (x .. "+" .. y .. "=" .. result)
end
-- Call the function a few times
AddAndPrint(2, 3, 7) -- Will print 2+3=5
AddAndPrint(4, 5, 8, 9, 10) -- Will print 4+5=9
AddAndPrint(6, 7, 11, 12, 14) -- Will print 6+7=13
On the other hand, if you add less arguments than the declaration has, the missing variables will get a value of nil:
-- Declare the function, takes two arguments
function PrintValues(x, y)
print ("x: " .. tostring(x) .. ", y: " .. tostring(y))
end
-- Call the function a few times
PrintValues(3, 4) -- will print x: 3, y: 4
PrintValues(1) -- will print x: 1, y: nil
PrintValues() -- will print x: nil, y: nil
In this code listing, x and y are passed to a tostring function before being concatenated to the string that will print. The tostring function is built into Lua; it needs to be called to avoid the error generated when attempting to concatenate nil to a string.
推薦閱讀
- Flask Web全棧開發(fā)實(shí)戰(zhàn)
- Learning Microsoft Windows Server 2012 Dynamic Access Control
- C及C++程序設(shè)計(jì)(第4版)
- Python快樂編程:人工智能深度學(xué)習(xí)基礎(chǔ)
- 程序設(shè)計(jì)與實(shí)踐(VB.NET)
- 樂學(xué)Web編程:網(wǎng)站制作不神秘
- 看透JavaScript:原理、方法與實(shí)踐
- Selenium Design Patterns and Best Practices
- Object-Oriented JavaScript(Second Edition)
- Python Geospatial Development(Second Edition)
- Mastering RStudio:Develop,Communicate,and Collaborate with R
- 數(shù)據(jù)結(jié)構(gòu)習(xí)題解析與實(shí)驗(yàn)指導(dǎo)
- AIRIOT物聯(lián)網(wǎng)平臺(tái)開發(fā)框架應(yīng)用與實(shí)戰(zhàn)
- 分布式數(shù)據(jù)庫原理、架構(gòu)與實(shí)踐
- 超好玩的Scratch 3.5少兒編程