DAY 16
0
Software Development

# 回傳多值/多值返回

Lua函數可以返回多值。在我看來，這個特性是特殊的，只有少數語言真正做到多值返回。什麼意思？這表示在接收一個函數的返回值，可以輕易忽略掉主要值以外的結果。這些結果一般用於輔助，絕大多數時候，我們不關心、不需要，但有時候非常有作用。

``````_d = {}
_v = _d.get("key", "value")

print(_v) # => Output: value
``````

``````found = "key" in _d
``````

``````function get(dict, key, default)
if dict[key] ~= nil then
return dict[key], true
else
return default, false
end
end
``````

``````function get(dict, key, default)
return (dict[key] or default), dict[key] ~= nil
end
``````

``````_d = {}
_v = get(_d, "key", "value")
print(_v) -- => Output: value
``````

``````_d = {}
_v, found = get(_d, "key", "value")
print(_v) -- => Output: value
print(found) -- => Output: false
``````

``````(defvar *h* (make-hash-table :test 'equal))
(multiple-value-bind
(_v found) (gethash 'key *h* "value")
(print _v)  ;; => Output: value
(print found)) ;; => Output: Nil
``````

## Python

``````def get(_d:dict, key, default):
return _d.get(key, default), key in _d

_d = {}
_v, found = get(_d, "key", "value")
print(_v, found) # => value True

_v = get(_d, "key", "value")
print(_v) # => ('value', False)
``````

# Golang

``````package main

import (
"fmt"
)

func main() {
v, _ := get()
fmt.Println(v)
}

func get() (int, bool) {
return 1, true
}
``````

``````package main

import (
"fmt"
)

func main() {
m := make(map[string]int)
v := m["key"]
fmt.Println(v)  // Output: 0
}
``````

map會返回預設的零值，整數的零值就是`0`。此外其實還會返回一個是否查找到的值：

``````package main

import (
"fmt"
)

func main() {
m := make(map[string]int)
v, ok := m["key"]
fmt.Println(v, ok)  // Output: 0 false

m["key"] = 50

v, ok = m["key"]
fmt.Println(v, ok) // Output: 50 true
}
``````

# 具名參數

``````function Person(info)
local person = {}
person.name = info.name or "Bob"
person.age = info.age or 20
return person
end

p1 = Person {
name = "Tina",
age = 13,
}

print("Name:    ", p1.name)
print("Age:     ", p1.age)
``````

Name: Tina
Age: 13

## 位置參數

``````function Person(args)
local person = args
person.name = args.name or "Bob"
person.age = args.age or 20
return person
end

p1 = Person {
"位置參數1",
age = 13,
"位置參數2",
}

print("Name:    ", p1.name)
print("Age:     ", p1.age)
print("-------------")
print("位置參數：", p1[1], p1[2])
``````

Name: Bob
Age: 13