Continue in Lua

Lua 是没有 continue 关键字的,Lua 的作者 Roberto 在 mail list 提到过原因:

Continue, on the other hand, is a real feature. (It even changes the

syntax and the lexical.)  Our main concern with "continue" is that there

are several other control structures that (in our view) are more or

less as important as "continue" and may even replace it. (E.g., break

with labels [as in Java] or even a more generic goto.) "continue" does

not seem more special than other control-structure mechanisms, except

that it is present in more languages. (Perl actually has two "continue"

statements, "next" and "redo". Both are useful.)

有时候业务需要,就不得不靠我们自己去实现了。先来一个递归版本:

local function foo(i, max)

    if i == 5 then

        return foo(6, max) -- continue to i=6

    end

    print(i)

    if i == max then

        return

    else

        return foo(i+1, max)

    end

end

foo(1, 10)

优点是逻辑简单明了,缺点就是递归导致的栈溢出问题。再来一个性能优化的版本,也就是再套一层循环:

for i = 1,10 do

    -- 这个 repeat 循环在每个 for 循环下只会跑一次

    repeat

        -- 这个 break 跳出 repeat 循环,相当于 continue 的效果

        if i == 5 then break end

        print(i)

    until true

end

本文分享自微信公众号 - poslua(poslua)。
如有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。

点赞
收藏

评论区

加载中...

相关推荐

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

Luarocks 安装艰难过程

1.最好新建一个你自己的目录,然后把lua Luarocks都安装在这个文件夹下面,方便以后维护2.安装lua环境$wgethttp://www.lua.org/ftp/lua5.3.0.tar.gz $tarzxvflua5.3.0.tar.gz $cdlua5.3.0 $viMakefile 

Lua在Linux中获取UUID的方法

Lua 与php 性能测试说明文档

Lua 与php性能测试说明文档测试环境   192.168.10.30获取同一物品信息  读取redis localhost:6379PhpnginxredisLuanginxredisngx\_lua将lua嵌入到nginx,让nginx执行lua脚本,高并

Redis+Lua——他叫了外援

    Redis从2.6版本开始引入对Lua脚本的支持,通过在Redis服务器中嵌入Lua环境,Redis客户端可以使用Lua脚本,直接在服务端原子的执行多个Redis命令。Lua    Lua是一种轻量小巧的脚本语言,用标准C语言编写并以源代码形式开放,其设计目的是为了嵌入应用程序中,从而为应用程序提供灵活的扩展和定制功能。为

Lua之Lua变量类型

在上一节中说到了Lua的安装与变量(https://www.oschina.net/action/GoToLink?urlhttp%3A%2F%2Fwww.ttlsa.com%2Flua%2Fluainstallandluavariablettlsa%2F),这节说说Lua变量的类型。Lua在使用中不需要预先定义变量的类型。Lua中基本的类