AKever

导航

Lua 基础篇1

-----阶乘与数据的读取----------

function fact(n)
    if n == 0 then
        return 1
    else
        rturn n*fact(n-1)
    end
end

print("enter a number: ")
a = io.read("*number")
print(fact(a))

 ----------lua 退出命令--------------

end-of-file

--------删除一个全局变量------------

b = nil
--将b赋值nil, 就像从未使用过b这个变量一样

 -----Lua中的8中类型-----------------

nil; boolean; number; string; userdata; function; thread; table

-----lua 中的 boolean----------------

false和nil 为假,其他为真

-----lua 字符串中的转义序列----------

\a 响铃; \b退格; \f提供表格; \n换行; \r回车; \t水平tab; \v垂直tab; \\反斜杠; \"双引号; \'单引号

----lua ASCII转义序列--------------

\97 a; \10换行; \0492 12; 因为\49是1,后面2为数值,补足\<ddd>

------lua提供运行时数字和字符串的自动转换-------------

print("10"+1) --11
print("10+1") --10+1
print("-5.3e-10"*"2") ---1.06e-09
print("hello"+1) ---错误(不能转换"hello")

 ------lua 字符串的符号-------------------------

print(10 .. 20)  --1020, 字符串连接操作符(..) 
tostring(10) --数字转字符串

a="hello" 
print(#a) -->5  --获取字符串的长度
print(#"good\0bye") -->8

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

---------------lua table-------------------------

a = {}
a["x"] = 10
b = a    --b和a引用同一个table
print(b["x"]) --10
b["x"] = 20
print(a["x"]) --20
a = nil --现在b还在引用table
b = nil --再也没有对table的引用啦

--当一个程序在也没有对一个table的引用时,Lua的垃圾回收机制(garbage collector)最终会删除该table,并复用他的内存

a = {}
x = "y"
a[x] = 10 --将10放在字段"y"
print(a[x]) --10
print(a.x) --nil --字段"x"(未定义)的值
print(a.y) --10  --字段"y"的值
--以上注意 a的key是 "10"(string),也可以是number(数组, 线性表)

--数组 --读取10行内容,存储到table中

a = {}
for i=1, 10 do
    a[i] = io.read()
   --a[#a+1] = io.read()
end

 --相应的打印所有值

for i=1, #a do
    print(a[i])
end

--数组的操作

print(a[#a]) --打印最后一个值
a[#a] = nil --删除最后一个值
a[#a+1] = v --在列尾添加值v

 --返回table最大的索引数

table.maxn(a)

 --do--end

do 
    local a2 = 2*a
    local d = (b^2 - 4*a*c)^(x/2)
    x1 = (-b+d)/a2
    x2 = (-b-d)/a2
end
print(x1, x2)
--遇到do不执行,遇到end时才执行

 ==========默认值或数据类型的检测=========================

--数据的检测
w = Window {
    x=0, x=0, width=300, height=200,
    title="Lua", background="blue",
    border=true
}
function Window(options)
    --检查必要的参数
    if type(options.title) ~= "string" then
        error("no title")
    elseif type(options.width) ~= "number" then
        error("no width")
    elseif type(options.height) ~= "number" then
        error("no height")
    end
end
--默认值
_Window(options.title,
    options.x or 0, --默认值
    options.y or 0, --默认值
    options.background or "width" --默认值
    options.border  --默认值为false(nil)
    )

 

posted on 2014-08-01 14:21  AKever  阅读(328)  评论(0)    收藏  举报