SYNTAX
1、if else用法比较简单, 类似于C语言, 不过此处需要注意的是整个if只需要一个end,
哪怕用了多个elseif, 也是一个end.
例如
if op == "+" then
r = a + b
elseif op == "-" then
r = a - b
elseif op == "*" then
r = a*b
elseif op == "/" then
r = a/b
else
error("invalid operation")
end
SYSTEM
1、Lua对Table占用内存的处理是自动的, 如下面这段代码
a = {}
a["x"] = 10
b = a -- `b' refers to the same table as `a'
print(b["x"]) --> 10
b["x"] = 20
print(a["x"]) --> 20
a = nil -- now only `b' still refers to the table
b = nil -- now there are no references left to the table
b和a都指向相同的table, 只占用一块内存, 当执行到a = nil时, b仍然指向table,
而当执行到b=nil时, 因为没有指向table的变量了, 所以Lua会自动释放table所占内存
FUNCTION
1、不定参数
-- Functions can take a
-- variable number of
-- arguments.
function funky_print (...)
for i=1, arg.n do
print("FuNkY: " .. arg)
end
end
funky_print("one", "two")
运行结果
FuNkY: one
FuNkY: two
程序说明
* 如果以...为参数, 则表示参数的数量不定.
* 参数将会自动存储到一个叫arg的table中.
* arg为local变量,在一个function内
* arg.n中存放参数的个数. arg[]加下标就可以遍历所有的参数.
2、把Lua变成类似XML的数据描述语言
function contact(t)
-- add the contact ‘t’, which is
-- stored as a table, to a database
end
contact {
name = "64bit baboosh",
email = "asdic.xxs@gmail.com",
url = http://blog.youkuaiyun.com/tcxxs,
quote = [[
There are
10 types of people
who can understand binary.]]
}
contact {
-- some other contact
}
程序说明
* 把function和table结合, 可以使Lua成为一种类似XML的数据描述语言
* e09中contact{...}, 是一种函数的调用方法, 不要弄混了
* [[...]]是表示多行字符串的方法
* 当使用C API时此种方式的优势更明显, 其中contact{..}部分可以另外存成一配置文件
3、Lua的函数可以有多个参数, 也可以有多个返回值, 这都是由栈(stack)实现的.
需要调用一个函数时, 就把这个函数压入栈, 然后顺序压入所有参数, 然后用
lua_call()调用这个函数. 函数返回后, 返回值也是存放在栈中. 这个过程和
汇编执行函数调用的过程是一样的.