(Reference: https: //www.runoob.com/lua/lua-tutorial.html)
First, the basic
1 Print
print("Hello") print(123)
operation result:
Hello
123
2 comments
- Line Mark, single-line comment - [[ multiline comment MANY Line Mark ]] -
3, variable assignment
- default global variables Print (B) B = 10 Print (B) HTML = [[ . 1A 2BC 3DEF 4G QWE ]] Print (HTML)
operation result:
nil
10
1a
2bc
3def
4g
qwe
4, and the connection string number plus
= A ' . 1 ' B = 2 - + are by digital processing Print (A + B) - This is the string concatenation Print (A .. B)
operation result:
3.0
12
5, arrays, lists
--tab used either when the array, may be used as a map
- Lua subscript 1 starting from
tab1 = {"a","b","c"} for k in pairs(tab1) do print(k .. ":" .. tab1[k]) end
operation result:
1:a
2:b
3:c
6, circulation
- the initial value, the cutoff value, the step size (default. 1) for I = 10 , . 1 , - 2 do Print (I) End - except pairs, ipairs iteration may be A = { " One " , " TWO " , " Three " } - Lua script "on line", plus the ";" on the semicolon for I, V in ipairs (A) do Print (I, V); Print (I .. " : " . . v) End
operation result:
10
8
6
4
2
1 one
1:one
2 two
2:two
3 three
3:three
7, if determined
--0是true if(0) then print("0 is true") end num = 100 --if else的使用 if(num<20) then print("num < 20") else print("num >= 20") end print("num value is :", num) --多重判断 -- if then elseif then else end
operation result:
0 is true
num >= 20
num value is : 100
8, string search
--返回值startIndex,endIndex,start 1 s,e=string.find("www.runoob.com", "run") print(s,e)
operation result:
5 7
Second, the function call
1, defined functions, and calls
function max(num1, num2) if(num1 > num2) then result = num1 else result = num2 end return result end print("the max is:", max(10, 4)) print("the max is:", max(5,6))
operation result:
the max is: 10
the max is: 6
2, as a function of transmission parameters
myprint = function(param) print("This is print function - ##", param, "##") end function add(num1, num2, funcPrint) result = num1 + num2 funcPrint(result) end myprint(100) add(2,5,myprint)
operation result:
This is print function - ## 100 ##
This is print function - ## 7 ##
3, variable length parameters passed
--not fix args num function add_many(...) local s = 0 for i,v in ipairs{...} do s = s+v end return s end print(add_many(1,2,3,4,5))
operation result:
15
4, the length of the variable length parameter
a, by obtaining a length #arg
b, the length by obtaining select ( "#", ...)
function average(...) local res = 0 local arg = {...} for i,v in ipairs(arg) do res = res + v end --#arg or select("#", ...) print("arg num is:" .. #arg .. ".") return res/#arg end print(average(1,2,3,4,5))
operation result:
arg num is:5.
3.0