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

  • 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.

主站蜘蛛池模板: 旅游| 民和| 上饶市| 新疆| 宜都市| 邓州市| 尚义县| 梁平县| 高邑县| 运城市| 富顺县| 天柱县| 张家界市| 宜阳县| 开阳县| 高安市| 宜君县| 大余县| 台南市| 焦作市| 邻水| 饶河县| 寿光市| 湘潭县| 潮州市| 从江县| 武威市| 汽车| 东宁县| 涿鹿县| 西乌珠穆沁旗| 武山县| 中西区| 达孜县| 利津县| 梁山县| 吉首市| 来凤县| 宜城市| 浮梁县| 白城市|