-- example of an anonymous function
-- returned as a value
-- see http://www.tecgraf.puc-rio.br/~lhf/ftp/doc/hopl.pdf
function add(x)
return function (y) return (x + y) end
end
f = add(2)
print(type(f), f(10))
function 12
Lua 线程。线程是通过调用内嵌函数 coroutine.create(f) 创建的一个协同例程 (co-routine),其中 f 是一个 Lua 函数。线程不会在创建时启动;相反,它是在创建之后使用 coroutine.resume(t) 启动的,其中 t 就是一个线程。每个协同例程都必须使用 coroutine.yield() 偶尔获得其他协同例程的处理器。
赋值语句。Lua 允许使用多种赋值语句,可以先对表达式进行求值,然后再进行赋值。例如,下面的语句:
i = 3
a = {1, 3, 5, 7, 9}
i, a[i], a[i+1], b = i+1, a[i+1], a[i]
print (i, a[3], a[4], b, I)
-- defines a factorial function
function fact (n)
if n == 0 then
return 1
else
return n * fact(n-1)
end
end
print("enter a number:")
a = io.read("*number")
print(fact(a))
$ lua
> -- create an empty table and add some elements
> t1 = {}
> t1[1] = "moustache"
> t1[2] = 3
> t1["brothers"] = true
> -- more commonly, create the table and define elements
> all at once
> t2 = {[1] = "groucho", [3] = "chico", [5] = "harpo"}
> t3 = {[t1[1]] = t2[1], accent = t2[3], horn = t2[5]}
> t4 = {}
> t4[t3] = "the marx brothers"
> t5 = {characters = t2, marks = t3}
> t6 = {["a night at the opera"] = "classic"}
> -- make a reference and a string
> i = t3
> s = "a night at the opera"
> -- indices can be any Lua value
> print(t1[1], t4[t3], t6[s])
moustache the marx brothers classic
> -- the phrase table.string is the same as table["string"]
> print(t3.horn, t3["horn"])
harpo harpo
> -- indices can also be "multi-dimensional"
> print (t5["marks"]["horn"], t5.marks.horn)
harpo harpo
> -- i points to the same table as t3
> = t4[i]
the marx brothers
> -- non-existent indices return nil values
> print(t1[2], t2[2], t5.films)
nil nil nil
> -- even a function can be a key
> t = {}
> function t.add(i,j)
>> return(i+j)
>> end
> print(t.add(1,2))
3
> print(t['add'](1,2))
3
> -- and another variation of a function as a key
> t = {}
> function v(x)
>> print(x)
>> end
> t[v] = "The Big Store"
> for key,value in t do key(value) end
The Big Store
-- Overload the add operation
-- to do string concatenation
--
mt = {}
function String(string)
return setmetatable({value = string or ''}, mt)
end
-- The first operand is a String table
-- The second operand is a string
-- .. is the Lua concatenate operator
--
function mt.__add(a, b)
return String(a.value..b)
end
s = String('Hello')
print((s + ' There ' + ' World!').value )
这段代码会产生下面的文本:
Hello There World!
函数 String() 接收一个字符串 string,将其封装到一个表({value = s or ''})中,并将元表 mt 赋值给这个表。函数 mt.__add() 是一个元方法,它将字符串 b 添加到在 a.value 中找到的字符串后面 b 次。这行代码 print((s + ' There ' + ' World!').value ) 调用这个元方法两次。
-- code courtesy of Rici Lake, rici@ricilake.net
function Memoize(func, t)
return setmetatable(
t or {},
{__index =
function(t, k)
local v = func(k);
t[k] = v;
return v;
end
}
)
end
COLORS = {"red", "blue", "green", "yellow", "black"}
color = Memoize(
function(node)
return COLORS[math.random(1, table.getn(COLORS))]
end
)
将这段代码放到 Lua 解释器中,然后输入 print(color[1], color[2], color[1])。您将会看到类似于 blue black blue 的内容。