Lua goto 用法举例

简介:
Lua支持goto语法, 但是有一定的局限性.
例如
1. 不能在block外面跳入block(因为block中的lable不可见), 
2. 不能跳出或者跳入一个函数. 
3. 不能跳入本地变量的作用域.
Lua poses some restrictions to where you can jump with a goto. First, labels
follow the usual visibility rules, so you cannot jump into a block (because a
label inside a block is not visible outside it). 
Second, you cannot jump out of
a function. (Note that the first rule already excludes the possibility of jumping
into a function.) 
Third, you cannot jump into the scope of a local variable.

例子 : 
vi lua
i = 0
::s1:: do
  print(i)
  i = i+1
end
if i>3 then
  os.exit()
end
goto s1


[root@db-172-16-3-150 ~]# lua ./lua 
0
1
2
3

但是以上用法在命令行中会失败, 因为命令行中的block和文件不一样, 一个文件就是一个大block(函数例外).
[root@db-172-16-3-150 ~]# lua
Lua 5.2.3  Copyright (C) 1994-2013 Lua.org, PUC-Rio
> i = 0
> ::s1:: do
>>   print(i)
>>   i = i+1
>> end
0
> if i>3 then
>>   os.exit()
>> end
> goto s1
stdin:1: no visible label 's1' for <goto> at line 1

在命令行中do end为一个block, 所以后面无法跳入.
goto在Lua中还可用于模拟continue , redo这种用法. 因为Lua目前没有continue和redo的用法.
i = 0
while i<10 do
  ::redo::
  i = i+1
  if i%2 == 1 then 
    goto continue 
  else 
    print(i)
    goto redo
  end
  ::continue::
end

不能跳入一个本地变量的作用域, 例如 : 
[root@db-172-16-3-150 ~]# cat lua 
do 
  goto notok1
  local i = 1
  print(i)
  ::notok1::  -- 本地变量的作用域内, 所以无法跳转
  i = i+ 1
  ::ok::  -- 本地变量的作用域结束, 所以可以跳转.
end
报错 : 
[root@db-172-16-3-150 ~]# lua ./lua 
lua: ./lua:6: <goto notok1> at line 2 jumps into the scope of local 'i'

相关文章
lua语言——特殊用法
lua语言——特殊用法
198 0
|
1月前
|
存储 NoSQL Redis
Redis的Lua脚本有什么作用?
Redis Lua脚本用于减少网络开销、实现原子操作及扩展指令集。它能合并操作降低网络延迟,保证原子性,替代不支持回滚的事务。通过脚本,代码复用率提高,且可自定义指令,如实现分布式锁,增强Redis功能和灵活性。
41 1
|
4月前
|
存储 NoSQL 关系型数据库
使用lua脚本操作redis
使用lua脚本操作redis
51 0
|
4月前
|
NoSQL Java Redis
Redis进阶-lua脚本
Redis进阶-lua脚本
65 0
|
2月前
|
缓存 NoSQL Java
【Redis】5、Redis 的分布式锁、Lua 脚本保证 Redis 命令的原子性
【Redis】5、Redis 的分布式锁、Lua 脚本保证 Redis 命令的原子性
63 0
|
3月前
|
算法 NoSQL Java
springboot整合redis及lua脚本实现接口限流
springboot整合redis及lua脚本实现接口限流
91 0
|
3天前
|
存储 缓存 NoSQL
深入浅出Redis(十):Redis的Lua脚本
深入浅出Redis(十):Redis的Lua脚本