[Zhuan]Lua about

Lua 程式開發筆記

明明我在用 Mac OSX 寫這篇文章,但是依慣例還是要用 FreeBSD 的安裝範例

安裝

# cd /usr/ports/lang/lua; make install distclean

語法

字串:

> print('aabbcc')
aabbcc
> print("aabbcc")
aabbcc
> print([[aabbcc]])
aabbcc
> print([=[aabbcc]=])
aabbcc

賦值:

> a, b, c, d = true, false, 1, 1 < 2
> print(a, b, c, d)
true    false    1    true

比較:

> print(1 == 1)
> print(1 ~= 1)  # 注意,不是用 !=

nil:

> a, b, c, d = 1, 2
> print(a, b, c, d)
1       2       nil     nil

and, or, not:

> print(1 and 1)
1
> print(nil or 1)
1
> print(not nil)
true

接續:

> print('Hello' .. 'World')
HelloWorld

計算長度:

> print(#'abcd')
4
> print(#'Hello, world!')
13
> aa = 'Hello, world!'
> print(#aa)
13
> print(string.len(aa))
13

註解:

> -- print('hello')
>
> --[[ 這是
>> 很長
>> 的註解]]
>

if:

> if 1 == 1 then print('aa') end
aa

while:

> while 1 == 2 do print('should never print') end
>

for:

> for i = 1, 3 do print(i) end
1
2
3
> for i = 1, 10, 2 do print(i) end
1
3
5
7
9
>

repeat(至少執行一次):

> repeat print('aa') until 1 < 10
aa

break:

> for a = 1, 10 do
>>  if a > 5 then
>>      break
>>  end
>>  print(a)
>> end
1
2
3
4
5
>

type:

> print(type(100))
number
> print(type('aa'))
string

函式

> function echo_aa()
>> print('aa')
>> end
> echo_aa()
aa

local variable:

> aa = 'global variable'
> function print_aa()
>> local aa = 'bb'
>> print(aa)
>> end
> print_aa()
bb
> print(aa)
global variable

注意以下兩段:

> -- do block 裡面的 local
> aa = 'global variable'
> do
>> aa = 'bb'
>> print(aa)
>> end
bb
> print(aa)
global variable
> -- 在 global 裡面硬寫 local 是沒有用的
> aa = 'global variable'
> local aa = 'bb'
> print(aa)
global variable

取代內建函式:

> orig_print = print
> function new_print(val)
>> orig_print('aa'..val)
>> end
> print = new_print
> print('cc')
aacc

另種函式寫法:

> print_aa = function()
>> print('aa')
>> end
> print_aa()
aa

local 函式:

> aa = function()
>> local print = function() print('aa') end
>> print('bb')
>> end
> aa()
aa

Tables

> aa = {['aa']='aa', ['bb']='bb', ['cc'] = 'cc'}
> print(aa['bb'])
bb
> -- 簡易寫法
> new_aa = {aa='aa', bb='bb', cc='cc'}
> print(new_aa['aa'])
aa
> -- 另種取值
> print(new_aa.aa)
aa
> -- 範例
> aa = {bb = {cc = true}}
> print(aa.bb.cc)
true

使用 ipairs 達成 number 為 key 的 table loop:

> aa = {'aa', 'bb', 'cc', 'dd'}
> for key, value in ipairs(aa) do
>> print(key .. ' -> ' .. value)
>> end
1 -> aa
2 -> bb
3 -> cc
4 -> dd

使用 pairs 達成 name 為 key 的 table loop:

> aa = {['aa']='aa', ['bb']='bb', ['cc'] = 'cc'}
> for key, value in pairs(aa) do
>> print(key .. ' -> ' .. value)
>> end
cc -> cc
aa -> aa
bb -> bb

一些 table 相關操作:

table.sort(TABLE)
table.insert(TABLE, new_item) 等同 TABLE[#TABLE + 1] = new_item
table.concat(TABLE) 連接字串
table.remove(TABLE) 移除最後一個 item
table.maxn(TABLE) 找出 key 最大正值

Tables 的物件導向:

> function aa()
>>  local function bb()
>>      return 'bb'
>>  end
>>  local function cc()
>>      return 'cc'
>>  end
>>  return {bb = bb, cc = cc}
>> end
> print(aa().bb())
bb
> print(aa().cc())
cc

或是:

> aa = {}
> function aa:print()
>> print('aa')
>> end
> aa:print()
aa

strings

一些用法:

string.lower('HELLO')
string.upper('hello')
string.reverse('hello')
string.rep('hello', 2)      #=> hellohello
string.sub('hello', 1, 4)   #=> hell
string.len('hello')         #=> 5
string.byte('ABCDE', 1, 5)  #=> 65 66 67 68 69
string.byte('A')            #=> 65
string.char(65)             #=> A
string.format(">>%15s%6d<<", 'abc', 123)   #=> >>             abc    123<<
string.gsub('The rain in Spain stays mainly in the plain.')     #=> The royn in Spoyn stays moynly in the ployn.
string.gsub('The rain in Spain stays mainly in the plain.', 999) #=> The royn in Spoyn stays moynly in the ployn.
string.gsub('The rain in Spain stays mainly in the plain.', '[ /,.-]', '') #=> TheraininSpainstaysmainlyintheplain
string.find('abc', 'b')     #=> 2
string.match('abc cde def', '%a+') #=> abc

io

io.write('hello') #=> hello

FileHnd, ErrStr = io.open('aa.txt', 'w')
FileHnd:write('hello')
FileHnd:close()

os.remove('aa.txt') #=> delete aa.txt

io.stdin()
io.stdin:read()
io.stdout()
io.stdout:write()
io.stderr()
io.lines('aa.txt')

command line

取 args 範例,將以下存為 select.lua:

#!/usr/bin/env lua
print((select('#', ...)))
print((select(1, ...)))
print((select(2, ...)))
print((select(3, ...)))

執行:

$ lua select.lua a b c
3
a
b
c

另外就是直接 lua 執行 string:

$ lua -e 'print("aa")'
aa

modules

modules 位置(以 unix 為例):

/usr/local/share/lua/5.1
/usr/local/lib/lua/5.1

所以:

export LUA_PATH='?.lua;/usr/local/lib/lua/5.1/?.lua'

使用 module 的語法為:

require('module_name')
require 'module_name'

撰寫 module (注意 namespace),如 Util.lua:

Util = {}

function Util.Quote(Str)
    return string.format('%q', Str)
end

return Util

為了避免 global variable 與 local 衝突,請使用 strict.lua,會強迫所有 global variable 都先行定義:

require 'strict'

local function Test()
    A = 2
    B = 3
end

A = 1
Test()
-- 會產生 assign to undeclared variable 'B' 的錯誤提醒

找出 global variable 的方式:

luac -l -p file_name.lua

multitask

用法仍須看文件:

coroutine.yield()
coroutine.resume()
coroutine.wrap()
coroutine.create()
coroutine.status()
coroutine.suspended()
coroutine.running()
coroutine.normal()
coroutine.dead()

使用 c lib

其實就是把編譯好的 .so 放到特定目錄中,但詳情還是要看官網

很多參考資料

http://www.lua.org/docs.html

posted on 2012-07-24 09:32  甲骨魚  阅读(207)  评论(0编辑  收藏  举报

导航