【Lua】【型別】 函數function
函數宣告
函數可以使用function來做宣告,並以end結束
function hello()
print("Hello, World")
end
-- 等同以下
hello = function()
print("Hello, World")
end
函數傳遞
function genFun()
return function()
print("Hello, World")
end
end
function callFun(f)
f()
end
local _f = genFun() -- # get a function
callFun(_f) -- print("Hello, World")
不定長參數
function hello(...)
local members = {...}
print("有多少成員: ", #members)
for _,m in pairs(members) do
print("Hello, "..m)
end
end
-- hello("Bob", "Lua", "Luna", "Selene")
-- 有多少成員: 4
-- Hello, Bob
-- Hello, Lua
-- Hello, Luna
-- Hello, Selene
立即呼叫函式表達式(IIFE) 與 匿名函式
(function ()
print("Hello, World")
end)()
多值返回
function get(dict, key, default)
return (dict[key] or default), dict[key] ~= nil
end
_d = {}
_v, found = get(_d, "key", "value")
print(_v) -- => Output: value
print(found) -- => Output: false
function Person(args)
local person = args
person.name = args.name or "Bob"
person.age = args.age or 20
person.address = args.address or ""
return person
end
p1 = Person {
"位置參數1",
age = 13,
address = "secret",
"位置參數2",
}
print("Name: ", p1.name)
print("Age: ", p1.age)
print("Address: ", p1.address)
print("-------------")
print("位置參數:", p1[1], p1[2])
Name: Bob
Age: 13
Address: secret
位置參數: 位置參數1 位置參數2
常用的內建函數
其實除此之外,還有很多應該是很常用的。不過先放個已經提到過,或是大概不會提到的。
基本
- ipairs
- pairs
- require
- tonumber
- tostring
- type
輸入/輸出
估計本系列不怎麼會提到,先放這XD。
- io.close
- io.input
- io.lines
- io.open
- io.output
- io.popen
- io.read
- io.stderr
- io.stdin
- io.stdout
- io.tmpfile
- io.type
- io.write
- file:close
- file:flush
- file:lines
- file:read
- file:seek
- file:write
哈...好像幾乎都蠻重要的...
數學
- math.abs
- math.ceil
- math.exp
- math.floor
- math.huge (無限大)
- math.log
- math.max
- math.maxinteger
- math.min
- math.mininteger
- math.pi (PI 常數)
- math.random
- math.randomseed
- math.tointeger
- math.type
作業系統
- os.clock
- os.date
- os.difftime
- os.execute
- os.exit
- os.getenv
- os.time
Lua 5.1前一個和
os.getenv很像的函數setfenv其實也蠻常用的,後來被移除,改用其他方式。
當前還有很多是使用Lua 5.1,這雖然是需要知道的事情,不過其實其與作業系統無關。
字串
- string.byte
- string.char
- string.find
- string.format
- string.len
- string.reverse
- string.sub
- utf8.char
- utf8.codes
- utf8.len