Lua 筆記


lua命令:

#enter shell

lua

#excute script file

lua xxx.lua

lua腳本:

#!/usr/local/bin/lua

核心概念:

As a extension language, Lua has no notion of  a 'Main’ program: it only works embedded in a host client, called the embedding program or simply the host. The host program can invoke functions to execute a piece of Lua code, can write and read Lua variables, and can register C functions to be called by Lua code.

Lua distrubition includes  a sample host program called lua, which uses the Lua library to offer a complete, standalone Lua interpreter, for interactive or batch use. 

Lua is a dynamically typed language. This means that variables do not have types; only values do. There are no type definitions in the language. All values carry their own type.

Lua can call functions written in Lua and functions written in C. Both are represented by the type function.

特性:

輕量級

可配置,可擴展

兼容性

 

類C的語言,大小寫敏感

在Lua中,一切都是變 量,除了關鍵字

特點:

  1. 變量名沒有類型,值才有類型,變量名在運行時可與任何類型的值綁定。
  2. 語言只提供唯一一種數據結構,稱為表(Table),它混合了數組、哈希,可以用任何類型的值作為key和value;提供了一致且富有表達力的表構造語法,使得Lua很適合描述復雜的數據。
  3. 函數是一等類型,支持匿名函數和正則尾遞歸(proper tail recursion)。
  4. 支持詞法界定(lexical scoping)和閉包(closure)。
  5. 提供thread類型和結構化的協程(coroutine)機制,在此基礎上可方便實現協作式多任務。
  6. 運行期能編譯字符串形式的程序文本並載入虛擬機執行。
  7. 通過元表(meta-table)和元方法(meta-method)提供的動態元機制(dynamic meta-mechanism),從而允許程序運行時根據需要改變或擴充語法設施的內定語義。
  8. 能方便地利用表和動態元機制實現基於原型(prototype-based)的面向對象模型。
  9. 從5.1版開始提供了完善的模塊機制,從而更好地支持開發大型的應用程序。

注釋:

單行:--

多行:--[[                        ]]

關鍵字:

and   break   do   else   elseif   end   false   for   function   if   in   local   nil   not   or   repeat   return   then   true   until   while

元表與元方法:

Every value in Lua can have a metetable. This meatball is an ordinary Lua table that define the behavior of the original value under certain special operations. You can change several aspects of the behavior of operations over a value by setting specific fields in its metatable. The keys in a meatball are derived from the event names; the corresponding values are called metamethods.

You can query the metatable of any value using the getmetatable function. You can replace the metatable of  tables using the setmetatable function. You can not change the metatable of other types from Lua code(except by using the debug library); you must use the C API for that.

Tables and full userdata have individual metatables. Values of all other types share one single meatball per type; that is, there is one single metatable for all numbers, one for all strings, etc. By default, a value has no metatable, but the string library sets a metatable for the string type.

變量類型: type(<var-name>) 

Nil   Boolean   Number   String   Function   Table   Thread   Userdata

========================================

Nil:

nil

Number:double

例子:

num = 234

num = 0.4

num = 4.57e-3

num = 0.3e12

num = 0xef45

函數:

tostr:

tostring(123)

String:‘’    “”   [[   ]]

例子:

’This is a "string".\n'

"This is a string.\n”

[[

string in line 'one'

string in line "two"

]]

[=[

string in line [[one]]

string in line [[two]]

]=]

函數:

拼接:

‘abc’..’def’

tonum:

tonumber(‘123’)

len:

print(#’12345') 

 

Boolean:

true,false

Condition - False:

false,nil

Function:

定義:

固定參數:

function <func-name>(<args>)

……

end

變長參數:

function <func-name>(…)

local args = {…}

…...

end

限制:

在Lua 里函數定義必須在調用之前執行,這是因為Lua里的函數定義本質上是變量賦值。

function foo() …… end

====

foo = function () …… end

參數傳遞:

在常用基本類型中,除Table是按地址傳遞外, 其它都是按值傳遞的。

返回值:

Lua中函數可以返回多個值,如下:

定義:

function swap(a, b)

return b, a

end

使用:

a, b = 1, 2

a, b = swap(a, b)

虛變量:

當一個方法返回多個值時,有些返回值有時候用不到,要是聲明很多變量來一一接收並不太合適,於是Lua提供了一個虛變量(dummy variable),以單個下划線(“_”)來命名,用它來丟棄不需要的數據,僅僅起到占位符的作用。

local start, finish = string.find(‘Hello’, ‘he’)

local start = string.find(‘Hello’, ‘he’)

local _, finish = string.find(‘Hello’, ‘he’)

函數與方法:

靜態方法和函數沒有區別:

func1(……)

table.static_method(……)

實例方法和靜態方法的唯一區別在於實例方法的第一個參數:

table.instance_method(table, ……)

table:instance_method(……)

動態調用:

定義:

local function doAction(method, …)

local args = {…} or {}

mothed(unpack(args, 1, table.maxn(args))

end

 使用:

local function run(x, y)

ngx.say(‘run’, x, y)

end

doAction(run, 1, 2)

Table:{} 關聯數組

說明:

Table是關聯數組,不僅可以使用整數來索引,還可以使用除了nil之外的其他值進行索引。

Lua 中的模塊、包、對象,元表均是使用table來表示的。

在Lua中,數組下標從1開始計數。

例子:

T1 = {[1]=‘one’, [2]=’two’}

one = T1[1]

T1[3] = ’three’

T1[‘four’] = 4

T1.four = 4

print(T1.four)

方法:

Thread:

Userdata:

作用域:

在默認情況下,函數外的變量總被認為是全局的,除非你在前面加上”local”;函數內的變量與函數的參數默認為局部變量。局部變量的作用域為從聲明位置開始到所在語句塊結束或者是直到下一個同名局部變量的聲明。變量的默認值均為 nil。

local a,b,c = 1,2,3 -- a,b,c都是局部變量  

迭代:

迭代文件:

io.lines()

迭代Table:

pairs(<value-of-table>)

邏輯:

算數:

+   -   *   /   ^   %

..

邏輯:

==   ~=   >   <   >=   <=

and   or   not

分組:

()

語句分割:

在Lua中,語句之間可以用分號";"隔開,也可以用空白隔開。

結構:

if-else:

if <condition> then

……

elseif <condition> then

…….

else

…….

end

for:

for i = <start>,<end>,<step> do

……

break

end

 

for i, v in pairs(<value-of-table>) do

…...

end

while:

while <condition> do

……

end

until:

repeat

……

until <condition>

function:

def:

function <func-name>(<args>)

……

end

call:

<func-name>(<args>)

closure:

 

return:

return <value>

multiple assign:

a, b, c = 1, 2, 3

模塊:

Lua 的模塊是由變量、函數等已知元素組成的 table。

引用模塊:

函數 require 有它自己的文件路徑加載策略,它會嘗試從 Lua 文件或 C 程序庫中加載模塊。

lua模塊:app/utils.lua

local utils = require “app.utils"

創建模塊:

lua模塊:app/utils.lua(/path/to/folder)

module("app.utils", package.seeall)

設置搜索路徑:以;為分割符

.lua - package.path - package.loadfile

package.path的默認值為LUA_PATH環境變量的值。

package.path = [[/path/to/folder/?.lua;]] .. package.path

.so - package.cpath - package.loadlib

package.cpath的默認值為LUA_CPATH環境變量的值。

互操作與嵌入:

與C語言的互操作:

在C函數中調用Lua腳本

在Lua腳本中調用C函數

在Host 程序中嵌入Lua:

Lua的官方實現完全采用ANSI C編寫,能以C程序庫的形式嵌入到宿主程序中。

標准庫:

basic:

環境:Lua將其所有的全局變量保存在一個常規的table中,這個table稱為“環境”。

_G — 全局環境表(全局變量)

_VERSION — 返回當前Lua的版本號

函數:

type (v)

print (…)

getmetatable (object)

setmetatable (table, metatable)

getfenv (f)

setfenv (f, table)

collectgarbage (opt [, arg])

require (modname) 

module(modname, package.seeall)

rawlen (v)

rawequal (v1, v2)

rawget (table, index)

rawset (table, index, value)

next (table [, index])

ipairs (table)

pairs (table)

dofile (filename)

load (func [, chunkname])

loadfile ([filename])

loadstring (string [, chunkname])

pcall (f, arg1, ···)

xpcall (f, err)

select (index, ···)

tonumber (e [, base])

tostirng (e)

unpack (list [, i [, j]])

assert (v [, message]) 

error (message [, level])

io: (.:)

io.close 

io.flush 

io.input 

io.lines 

io.open 

io.output 

io.popen 

io.read 

io.stderr 

io.stdin 

io.stdout 

io.tmpfile 

io.type 

io.write 

file:close 

file:flush 

file:lines 

file:read 

file:seek 

file:setvbuf 

file:write

string: (.)

string.upper

string.lower

table: (.)

table.insert

table.remove

table.sort

utf8: (.)

utf8.char

utf8.len

coroutine: (.)

coroutine.create

coroutine.status

debug: (.)

debug.debug

debug.getinfo

os: (.)

os.date

os.time

os.rename

os.remove

os.execute

package: (.)

package.path

package.cpath

package.loaded

math: (.)

math.abc

math.max

math.min

math.pi

math.random

C API:

輔助庫:

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM