# lua "诡异"的return用法

function a()
i = 1
return i  -- 这里会报错, 提示return后面必须是end, 意思是既然你要return了, 那么就结束这个块吧.
i = 2
end

> function a()
>>   i = 1
>>   return i
>>   i = 2
stdin:4: 'end' expected (to close 'function' at line 1) near 'i'

> function a()
>>   i = 1
>>   do return i end  -- 这里是允许的.
>>   i = 2
>> end
> print(a())
1

> if i == 1
>> then
>>   return  -- 这里不能使用, 因为下面不是elseif或者else或者end.
>>   i=2
stdin:4: 'end' expected (to close 'if' at line 1) near '='

if i == 1
then
return
elseif i == 2
then
return
else
return
end

-- 以上用法是可以的, return分别放在elseif, else, end前面. 拐点 结束前.

> for x=1,10,1 do
>> print(x)
>> return
>> print(x+1)
>> end
1
2

return后面换成赋值就报错了
> for x=1,10,1 do
print(x)
return
print(x+1)
x=2
stdin:4: 'end' expected (to close 'for' at line 1) near 'x'
> for x=1,10,1 do
print(x)
return
x=2
stdin:4: 'end' expected (to close 'for' at line 1) near '='

"诡异"来形容不为过.

> for x=1,10,1 do
print(x)
do return end
print(x)
x=2
>> end
1

> repeat do
i=1
print(i)
return
print(i)
end until i == 2
1
1
> repeat do
i=1
print(i)
return
print(i)
x=2   -- 这里又会报错.
end until i == 2
stdin:4: 'end' expected (to close 'do' at line 1) near 'x'

+ 订阅