zoukankan      html  css  js  c++  java
  • 《Programming in Lua 3》读书笔记(五)

    Lua:Statement

    Lua支持:赋值、控制结构、函数调用等,另外Lua也支持一些所谓“奇葩”的语句段,那就是多重赋值还有局部声明。

    4.1 Assignment
    基本的赋值同其他语言类似:

    a = "hello" .. "world"

    所谓“奇葩”的多重赋值:

    a,b = "hello","world"
    eg.
    a,b = "hello","world" print(a) --hello print(b) --world

    多重赋值的时候,多余的值会被舍弃,而不足补nil

    eg.
    a,b,c = 1,2,3,4          --4 会被舍弃
    a,b,c = 1,2               -- c 会被赋值nil

    作者也指出,多重赋值的速度亚于单一的赋值,所以一般在函数返回多个值的时候才会使用多重赋值。


    Local变量
    Local变量有其范围,因此可以使用local限定变量的有效范围,在某些编译环境下,会将每一行视为一个chunk,因此local的限定作用将会失效。此时的解决方案是使用关键字do-end来实现chunk:
    eg.

    do
         <chunk>
    end


    使用local变量的好处是拥有更快的速度,并且local变量出了chunk便会被系统收回内存使用。

    控制结构
    1、if then else结构
    eg.

    if <condition> then
         <body>
    else
         <body>
    end


    eg.注意此处不需要多余的end

    if <condition> then
         <body>
    elseif <condition> then
         <body>
    elseif <condition> then
         <body>
    else
         <body>
    end

    因为lua中没有switch语句,所以上述语句的使用一定程度上能达到switch的效果。

    2、while结构
    当while条件为真的时候循环

    while <condition> do
         <body>
    end


    3、repeat-until 结构
    循环,直到until的条件为真

    repeat
         <body>
    until <condition>


    4、for
    Numeric for 和Generic for

    Numeric for
    eg. 

    for var = exp1,exp2,exp3 do
         <body>
    end


    这个循环用var的值(起始值为exp1,结束值exp2,每一步变动值exp3)来执行循环体。要注意的是,exp1,2,3这三个值只会执行计算一次,并且var的语意范围只在循环体内部有效。
    提前结束循环可以使用break关键词。

    Generic for
    使用到了迭代器:迭代遍历文件每一行(io.lines);迭代遍历table(pairs);迭代遍历一组序列(ipairs);遍历字符串的每一个字符(string.gmatch)
    eg.

    Break、return、goto
    一般用break和return来跳出某个语句快,而goto则用来跳转到某个指定的函数。Lua中的goto使用恰当的话能发挥非常大的作用,这个需要注意一下。

  • 相关阅读:
    ADB命令大全
    Backup your Android without root or custom recovery -- adb backup
    Content portal for Pocketables Tasker articles
    Is there a way to detect if call is in progress? Phone Event
    Tasker to proximity screen off
    Tasker to detect application running in background
    Tasker to create toggle widget for ES ftp service -- Send Intent
    Tasker to proximity screen on
    Tasker to answer incoming call by pressing power button
    Tasker to stop Poweramp control for the headset while there is an incoming SMS
  • 原文地址:https://www.cnblogs.com/zhong-dev/p/4044581.html
Copyright © 2011-2022 走看看