Lua 函数的多值返回

30 views
Skip to first unread message

sagasw

unread,
Aug 9, 2009, 9:01:17 PM8/9/09
to lu...@googlegroups.com


Lua 函数多值返回需要我们注意一下:
1)处于 list of values / list of variables / list of arguments 的末尾,函数将提供尽可能多的值,这里的 list 中的元素使用 "," 分隔
2)处于其他情况下,函数将提供第一个返回值

Code
local function f()
    
return 123
end

-- list of values 的末尾,f() 提供尽可能多的值
local a, b, c = 4, f()
print(a, b, c)

-- 不在 list of values 的末尾,f() 提供一个值
local a2, b2, c2 = f(), 4
print(a2, b2, c2)

-- list of values 的末尾,f() 提供尽可能多的值
local a3, b3, c3 = f()
print(a3, b3, c3)

-- 不在 list of values 的末尾,f() 提供一个值
--
 f() .. xxx 不是一个 list
local a4 = f() .. 4
print(a4)

-- 不在 list of values 的末尾,f() 提供一个值
--
 xxx .. f() 不是一个 list
local a5 = 4 .. f()
print(a5)

-- a, b, c 构成一个 list
local function f2(a, b, c)
    
print(a, b, c)
end

-- list of arguments 的末尾,f() 提供尽可能多的值
f2(f())

-- list of arguments 的末尾,f() 提供尽可能多的值
f2(a, f())

-- 不在 list of arguments 的末尾,f() 提供一个值
f2(f(), 4)

3)强制获取一个函数的返回值

local function f()
    
return 123
end

-- 输出 1
print((f()))
Reply all
Reply to author
Forward
0 new messages