Lua - 基礎文法

來源:互聯網
上載者:User

標籤:

Hello World互動式編程

Lua 互動式編程模式可以通過命令 lua -i 或 lua 來啟用:

[[email protected] lua]$ luaLua 5.1.4  Copyright (C) 1994-2008 Lua.org, PUC-Rio> print("hello world")hello world
指令碼式編程

我們可以將 Lua 程式碼保持到一個以 lua 結尾的檔案,並執行,該模式稱為指令碼式編程,如我們將如下代碼儲存在名為 hello.lua 的指令檔中:

print("hello world")

使用 lua 命令執行以上指令碼,輸出結果為:

[[email protected] lua]$ lua hello.lua hello world

或者將代碼修改為如下形式來執行指令碼:

#!/usr/bin/luaprint("hello world")

為 hello.lua 添加可執行許可權,並執行

[[email protected] lua]$ chmod a+x hello.lua [[email protected] lua]$ ./hello.lua hello world
注釋

單行注釋:

-- 單行注釋

多行注釋:

--[[  多行注釋  多行注釋--]]

 

資料類型

Lua 是動態類型語言,變數不要類型定義,只需要為變數賦值。值可以儲存在變數中,作為參數傳遞或結果返回。

Lua 中有 8 個基本類型分別為:nil、boolean、number、string、userdata、function、thread 和 table。

資料類型 描述
 nil  只有值 nil 屬於該類,表示一個無效值(在條件運算式中相當於 false)
 boolean  包含兩個值:false 和 true
 number  表示雙精確度類型的實浮點數
 string  字串由一對雙引號或單引號來表示
 function  由 C 或 Lua 編寫的函數
 userdata   表示任意儲存在變數中的 C 資料結構
 thread  表示執行的獨立線程,用於執行協同程式
 table  

我們可以使用 type 函數測試給定變數或者值的類型:

print( type(nil) )                             -- nilprint( type(true) )                            -- booleanprint( type(10.4 * 3) )                        -- numberprint( type("Hello world") )                  -- stringprint( type(print) )                           -- functionprint( type({"a", "b", "c", "d"}) )            -- table
nil

nil 類型表示一種沒有任何有效值,它只有一個值 nil,例如列印一個沒有賦值的變數,便會輸出一個 nil 值:

> print(undefined_value)nil

對於全域變數和 table,nil 還有一個 “刪除” 作用,給全域變數或者 table 表裡的變數賦一個 nil 值,等同於把它們刪掉。

boolean

boolean 類型只有兩個可選值:true 和 false,Lua 把 false 和 nil 看作是 “假”,其他的都為“真”。

string

字串由一對雙引號或單引號來表示。

> print("it‘s ok")it‘s ok> print(‘This is a "hello world" program‘)This is a "hello world" program

也可以用 2 個方括弧 “[[]]” 來表示一塊字串。

html = [[<html>    <body>        <a href="http://www.lua.org/">Lua</a>    </body></html>]]

使用 “..” 拼接字串:

> print("hello" .. "world")helloworld

使用 “#” 計算字串長度:

> print(#"abcdefg")7

 

迴圈while 迴圈
while(condition)do   statementsend
for 迴圈數字 for 迴圈
for v = e1, e2, e3 do block end

v 從 e1 變化到 e2,每次變化以 e3 為步長遞增 v,並執行一次 block。e3 是可選的,如果不指定,預設為 1。

泛型 for 迴圈
for i, v in ipairs(a)do    -- do something with i & vend 

i 是數組索引值,v 是對應索引的數組元素值。ipairs 是 Lua 提供的一個迭代器函數,用來迭代數組。

repeat ... until 迴圈

repeat ... until 迴圈類似其他語言的 do ... while 迴圈。

repeat   statementswhile( condition )

 

條件控制

格式

if exp then block {elseif exp then block} [else block] end

 

函數

定義:

function max( a, b )    if a >= b     then         return a    else        return b    endend

多傳回值:

function maxmin( arr )    if #arr < 1    then        return nil, nil    end    local max = arr[1]    local min = arr[1]    for i, v in ipairs(arr) do        if arr[i] > max        then            max = arr[i]        end        if arr[i] < min        then            min = arr[i]        end    end    return max, minend

max, min = maxmin({2, 4, 3, 0, 1})

可變參數:

function average(...)    local sum = 0    local args = {...}    for i, v in ipairs(args) do        sum = sum + v    end    return sum/#argsendprint(average(1, 2, 3, 4))

 

運算子算術運算子

+、-、*、/、%、^(乘冪)

關係運算子

==、~=(不等於)、>、<、>=、<=

邏輯運算子

and、or、not

其他運算子

..(拼接字串)、#(計算字串或 table 的長度)

 

字串字串的常用操作
-- 字串全部轉為大寫字母string.upper("hello")                            -- HELLO-- 字串全部轉為小寫字母string.lower("HELLO")                            -- hello-- 替換字串string.gsub("tooth", "o", "e")                   -- teeth    2-- 尋找字串string.find("hello world", "or")                 -- 8    9-- 反轉字串string.reverse("Lua")                            -- auL-- 格式化字串string.format("%4d-%02d-%02d", 2016, 1, 1)       -- 2016-01-01-- 將整型數字轉成字元並串連string.char(97, 98, 99, 100)                     -- abcd-- 返回第一字元的 ASCII 值string.byte("ABCD")                              -- 65-- 返回第四字元的 ASCII 值string.byte("ABCD", 4)                           -- 68-- 返回字串長度string.len("lua")                                -- 3-- 返回字串的指定次數的拷貝string.rep("abc", 3)                             -- abcabcabc-- 拼接字串"dead" .. "line"                                 -- deadline

 

 

數組

執行個體:

#!/usr/bin/luaarray = {"a", "b", "c"}for i= 0, #array do    print(array[i])end

輸出為:

nilabc

在 Lua 索引值是以 1 為起始的,如果知道的索引沒有值則返回 nil。但是也可以使用 0 或負數作為索引:

#!/usr/bin/luaarray = {}for i= -1, 1  do    array[i] = i * 2endfor i= -1, 1  do    print(array[i])end

輸出為:

-202

 

Lua - 基礎文法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.