官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 台安县| 商都县| 疏勒县| 榆树市| 西盟| 萨迦县| 贵溪市| 长治县| 潢川县| 久治县| 农安县| 兰考县| 卓尼县| 通化市| 建水县| 石柱| 海盐县| 新化县| 香格里拉县| 井陉县| 阜宁县| 壤塘县| 商洛市| 合肥市| 贺州市| 那曲县| 丹寨县| 都兰县| 襄城县| 诏安县| 东海县| 通州市| 平定县| 新化县| 河池市| 淮阳县| 潞城市| 潜江市| 汉源县| 永春县| 旬阳县|