string.byte此示例代码中返回的数据类型如下:
s = string.byte("hello", 1, 6)
Run Code Online (Sandbox Code Playgroud)
type(s)返回"number",但为什么print输出6个数字而不是1?
string.byte如果您告诉它,则返回多个数字.原因print是显示五个数而不是一个是因为它捕获了所有返回值,而使用赋值时,只使用第一个值而其余的被丢弃.
local h = string.byte'hello' -- 104, returns only the first byte
local e = string.byte('hello', 2) -- 101, specified index of 2
local s = string.byte('hello', 1, 6) -- 104 101 108 108 111,
-- but s is the only variable available,
-- so it receives just 104
local a, b = string.byte('hello', 1, 6) -- same thing, except now there are two
-- variables available, thus:
-- a = 104 & b = 101
print(string.byte('hello', 1, 6))
Run Code Online (Sandbox Code Playgroud)
104 101 108 108 111
print(string.byte('hello', 1, 6), 0) -- in this case, only the first value from
-- the multiple return is used because there
-- is another argument after the results
Run Code Online (Sandbox Code Playgroud)
104 0
我建议阅读Lua中多个结果和vararg表达式的工作原理.
[...]如果在另一个表达式内或表达式列表的中间使用了vararg表达式,则将其返回列表调整为一个元素.如果表达式用作表达式列表的最后一个元素,则不进行任何调整(除非最后一个表达式括在括号中).