lua笔记(1)

来源:互联网 发布:网络用语野生什么意思 编辑:程序博客网 时间:2024/05/21 17:22

一、lua中的数据类型

1、数值


a = 1

b = 1.2


2、字符串


c = "hello world"


3、布尔


d = true

f = false


4、表(Table) = 数组+映射

4.1、数组


a = {}

a[1] = 10

a[2] = "hello"

a[3] = true


--or


a = {10, "hello", true}


4.2、映射


a = {}

a["hello"] = 1

a[3] = false


--or


a = {

    ["hello"] = 1,

    [3] = false

}


二、函数

单返回值示例:


function add(a, b)

    local c = 1

    return a + b + c

end


其中的 c 只在函数内部有效


多返回值示例:


function addTwo(a, b)

        c = 1

    return a + b, a - b

end

--调用

a, b = addTwo(1, 2)


其中的 c 全局有效(应尽量避免这种写法)


三、表达式

and、or、not、..用法示例:


a = true and false

b = true or false

c = not true

d = "a".."b"


四、if语句

格式为:


if 表达式 then

    代码块一

elseif 表达式 then

    代码块二

else

    代友块三

end


五、while语句

格式为:


while 表达式 do

    循环体

end


六、for语句

1、循环


for i = 10, 1, -1 do

    print(i)

end


2、遍历


a = {

    ['foo'] = 1,

    [100] = true

}

for k, v in pairs(a) do

    print(k, v)

end


其中pairs()为迭代器,类似的还有 ipairs() 迭代器,ipairs()只迭代Table中的数组部分


七、包(package)

示例:

foo.lua文件:


local class = {}


function class.foo(a, b) 

    return a + b

end


return class


调用这个包:


local c = require("foo")

print(c.foo(1, 2))


注:这两个文件要在同一目录下


八、系统库

1、取对象长度:#t

2、table系列方法:


table.insert(t, index)

table.remove(t, index)

table.sort

table.move

table.pack

table.uppack

table.concat


3、字符串格式化:string.format("hi %d", 2)

4、数值转为字符串:tostring(3.14)

5、字符串转数值:tonumber("3.14")

6、删除映射:


local t = {}

t.a = 1

t.b = 2

--删除t.a用

t.a = nil


7、判断对象类型:type(t)

原创粉丝点击