lua学习(一)基础语法

hello.lua

global_val = 5

-->>>>>>>>>>>>>>>>>>>>> 表
local corp={
    12345, -->lua从1开始
    web = "www.baidu.com",
    tel = "1234567",
    staff={"Jack","Scott","Gary"},
    10086,
    100191,
    [10] = 360,
    ["city"] = "Beijing"
}
print(corp.city)
print(corp["city"])

print(corp[0])
print(corp[1])
print(corp[10])
print("表的长度:"..table.getn(corp)) --> 表中的nil值可能被当作是表的结束, 因此在删除操作时要进行,尽可能直接remove,而不是置为nil
corp[#corp+1] = "Shanghai"
print("表的长度:"..table.getn(corp))
corp["race"] = "black"
print("表的长度:"..table.getn(corp))
print(corp.race)

for i,v in ipairs(corp) do
    print("corp:"..v)
end
--> #返回的table长度应该就是nil之前的一个位置所对应长度
local littleT = {10086,123333}
str_concat = table.concat(littleT)
print("表连接结果:"..str_concat)

print("表最大长度:"..table.maxn(corp))

-- print("表删除的元素:"..table.remove(corp,5)),超过了#返回的表的长度就报错
print("表删除的元素:"..table.remove(corp,4))
print("表最大长度:"..table.maxn(corp))
print("表的长度:"..#corp)
print("表删除的元素:"..table.remove(corp))
print("表的长度:"..#corp)

--> 表的排序
local function compare(x,y)
    return x > y
end

local a = {1,7,4,5,2}
table.sort(a)
print("排序后的表"..a[1], a[2], a[3], a[4], a[5])
a = {1,7,4,5,2}
table.sort(a,compare)
print("排序后的表"..a[1], a[2], a[3], a[4], a[5])
-->>>>>>>>>>>>>>>>>>>>>字符串
str_len = "www.baidu.com" --> #计算字符串的长度,放在字符串前面
print(#str_len)

str_tsub = "123456789"
print("字符串截取"..string.sub(str_tsub,1,4)) --> sub()函数会创建子串
print("字符串ID:"..(string.sub(str_tsub, 1, 4)))
--> string.byte()可以直接返回字符串中某个字符的ASCII值,因此用于字符对比等操作时十分方便
print(string.byte("abc", 1, 3))
print("字符串ASCII值:"..string.byte("abc", 1, 3))
print(string.char(96, 97, 98))
print(string.len("hello lua"))

local find = string.find
print(find("abc cba", "ab"))
print(find("abc cba", "ab", 2))     -- 从索引为2的位置开始匹配字符串:ab
print(find("abc cba", "ba", -1))    -- 从索引为7的位置开始匹配字符串:ba
print(find("abc cba", "ba", -3))    -- 从索引为5的位置开始匹配字符串:ba
print(find("abc cba", "(%a+)", 1))  -- 从索引为1处匹配最长连续且只含字母的字符串
print(find("abc cba", "(%a+)", 1, true)) --从索引为1的位置开始匹配字符串:(%a+)

print(string.match("hello lua", "lua"))
print(string.match("lua lua", "lua", 2))  --匹配后面那个lua
print(string.match("lua lua", "hello"))
print(string.match("today is 27/7/2015", "%d+/%d+/%d+"))

s = "hello world from Lua"
for w in string.gmatch(s, "%a+") do  --匹配最长连续且只含字母的字符串
    print(w)
end

print("Hello".."World")
print(0 .. 1)-->print(0..1)会让编译器疑惑是不是数字,从而报错
print("hehe"..2333)
str1 = string.format("%s-%s","Hello","World!")
-- str2 = string.format("%s-%s-s%","Hello"," ","World!") --> 连续这样连接好像是不行的
str3 = string.format("%d-%s-%.3f",123,"world",1.21)
print(str1)
print(str2)
print(str3)
-->>>>>>>>>>>>>>>>> 逻辑运算
--[[
a and b 如果 a 为 nil,则返回 a,否则返回 b;
a or b 如果 a 为 nil,则返回 b,否则返回 a。
所有逻辑操作符将 false 和 nil 视作假,其他任何值视作真,
对于 and 和 or,“短路求值”,对于 not,永远只返回 true 或者 false。
在Lua 中, nil 和 false 为“假”,
其它所有值均为“真”。比如 0 和空字符串就是“真”。
nil 是一种类型,Lua 将 nil 用于表示“无效值”。
一个变量在第一次赋值前的默认值是 nil,将 nil 赋予给一个全局变量就等同于删除它。
]]
local num
print(num)
num = 110
print(num)

local c = nil
local d = 0
local e = 100

print(c and d)
print(c or e)
print(d and e)
print(d or e)
print(not c)
print(not d)
-->>>>>>>>>>>>>>>>>> 选择和循环
score = 90
if score == 100 then
    print("Ok")
elseif score >= 60 then
    print("Just so so")
else
    print("Sorry")
end

--> lua没有continue,但是还是有break的
x = 1
sum = 0
while x <=5 do
    sum = sum+x
    x = x+1
end

print(sum)

local t ={1,3,5,8,18,21}

local i
print(i)
for i,v in ipairs(t) do
    if 18 == v then
        print("index["..i.."] have right value[18]")
        break
    end
end

--[[
执行 repeat 循环体后,直到 until 的条件为真时才结束
]]

x = 10
repeat
    print(x)
    x = x+1
until x > 20

for i=1,5 do
    print(i)
end

for i = 1,10,3 do
    print(i)
end

for i=10,1,-1 do
    print(i)
end


--[[
Lua 的基础库提供了 ipairs,这是一个用于遍历数组的迭代器函数。
在每次循环中,i 会被赋予一个索引值,同时 v 被赋予一个对应于该索引的数组元素值。
]]
local a = {"a","b","c","d"}
for i,v in ipairs(a) do
    print("index:",i,"value:",v)
end

local days = {
    "Monday", "Tuesday", "Wednesday", "Thursday",
    "Friday", "Saturday","Sunday"
}

local revDays = {}
for k, v in pairs(days) do
    revDays[v] = k
end

-- print value
for k,v in pairs(revDays) do
    print("k:", k, " v:", v)
end

--> goto实现continue功能
for i=1, 3 do
    if i <= 2 then
        print(i, "yes continue")
        goto xcontinue
    end

    print(i, " no continue")

    ::xcontinue::
    print([[i'm end]])
end

local m = math.max(1,5)
print(m)

foo = 1

-->>>>>>>>>>>>>>>>>>>>> lua函数
local function foo0() -->函数
    print("in the function foo0")
end

local foo1 = function()
    print("in the function foo1")
end

foo0()
foo1()

--> lua函数不支持参数默认值,可以使用or进行实现
function default_fun(n)
    n = n or 0
    print(n)
end

default_fun(1)
default_fun()

--> lua里可以以匿名函数的方式通过参数传递
function testFun(tab,fun)
    for k,v in pairs(tab) do
        print(fun(k,v))
    end
end

tab = {key1="val1",key2="val2"};
testFun(tab, function(key, val)
    return key .. "=" .. val
end
)

--> lua函数可以返回多个值
function mulitReturn()
    return 1,2,3
end

print(mulitReturn())

--> 当一个函数有一个以上返回值,且函数调用不是一个列表表达式的最后一个元素,那么函数调用只会产生一个返回值, 也就是第一个返回值。
local function init()       -- init 函数 返回两个值 1 和 "lua"
    return 1, "lua"
end

local x, y, z = init(), 2   -- init 函数的位置不在最后,此时只返回 1
print("函数返回值:"..x, y, z)

local a, b, c = 2, init()   -- init 函数的位置在最后,此时返回 1 和 "lua"
print("函数返回值:"..a, b, c)

--> 函数调用的实参列表也是类似的
print("函数返回值:"..init(), 2)
print("函数返回值:"..2,init())
print("函数返回值:"..2, (init())) --> 使用括号的话就可以确定只使用到第一个返回值

--> lua函数可以使用可变数目的参数
function add(...)
    local s = 0
    for i,v in ipairs{...} do --> {...}表示一个由所有变长参数构成的数组
        s = s+v
    end

    return s
end

print(add(1,2,3))

function average(...)
    result = 0
    local args={...}

    for i,v in ipairs(args) do
        result = result + v
    end

    print("总共传入"..select("#",...).."个数")
    return result/#args --> #args和select("#",...) 可以获取可变参数的数量
end

print(average(10,3,5,6))

--> 包含固定参数的变长参数函数
function fwrite(fmt,...)
    return io.write(string.format(fmt,...))
end

fwrite("runnoob\n")
fwrite("%d%d\n",1,2)

--> 全动态函数调用
local function run(x,y)
    print('run',x,y)
end
local function attack(targetId)
    print('targetId',targetId)
end

local function do_action(method,...)
    local args = {...} or {}
    method(unpack(args,1,table.maxn(args)))
end

do_action(run,1,2)
do_action(attack,111)

--> unpack( )函数是接受一个数组来作为输入参数,并默认从下标为1开始返回所有元素
local t = {"a","b","c","d"}
print(unpack(t))
--> 运行结果:
--> a   b   c   d
print(unpack(t,2))
--> b c d

-->>>>>>>>>>>>>>>>>>>>>>> lua模块
--> lua加载模块,require 用于搜索 Lua 文件的路径是存放在全局变量 package.path 中,当 Lua 启动后,
--> 会以环境变量 LUA_PATH 的值来初始这个环境变量。如果没有找到该环境变量,则使用一个编译时定义的默认路径来初始化。
require("module")
print(module.constant)
module.func1()
module.func3()
-->>>>>>>>>>>>>>>>>>>>>>>> 对lua全局变量和局部变量的理解
print(a) --打印变量nil
a=111 --全局变量(整个lua文件中都可以使用,向下的范围)

do
    local a=0--局部变量在语句块的结束
    a=1 --局部变量优先
    print(a)--局部变量
    print(b) --打印变量nil
    b=222 --全局变量(整个lua文件中都可以使用,向下的范围)
end

function fun()
    local  c = 333 --局部变量
    d = 444 --全局变量
end

print(a)
print(b)
print(c)
print(d)

print("----需要调用函数,否则全局变量d没有值--")
fun()
print(c)
print(d)
-->>>>>>>>>>>>>>>>>>>>>>>>>>>>> 时间
print("返回当前时间:"..os.time())
--> 返回 t1 到 t2 的时间差,单位为秒
local day1 = { year = 2015, month = 7, day = 30 }
local t1 = os.time(day1)
print(os.date("%x%X"))

local day2 = { year = 2015, month = 7, day = 31 }
local t2 = os.time(day2)
print("时间差为:"..os.difftime(t2, t1))

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 数学
--> 另外使用 math.random() 函数获得伪随机数时,如果不使用 math.randomseed() 设置伪随机数生成种子或者设置相同的伪随机数生成种子,那么得到的伪随机数序列是一样的。
math.randomseed (100) --把种子设置为100
print(math.random())
print(math.random(100))
print(math.random(100, 360))
print(math.random(360))
--> 用时间作为种子设置随机值,math.random ([m [, n]])返回一个在区间[m, n]内均匀分布的伪随机整数
math.randomseed (os.time())   --把100换成os.time()
print(math.random())          -->output 0.88946195867794
print(math.random(100))       -->output 68
print(math.random(100, 360))  -->output 129

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> lua文件操作
--> 隐式文件描述。设置一个默认的输入或输出文件,然后在这个文件上进行所有的输入或输出操作。所有的操作函数由 io 表提供。
file = io.input("main.lua")    -- 使用 io.input() 函数打开文件

repeat
    line = io.read()            -- 逐行读取内容,文件结束时返回nil
    if nil == line then
        break
    end
    print(line)
until (false)

io.close(file)                  -- 关闭文件

file = io.open("main.lua", "a+")   -- 使用 io.open() 函数,以添加模式打开文件
io.output(file)                     -- 使用 io.output() 函数,设置默认输出文件
io.write("\nprint(\"hello world\")")           -- 使用 io.write() 函数,把内容写到文件
io.close(file)

--> 显式文件描述。使用 file:XXX() 函数方式进行操作, 其中 file 为 io.open() 返回的文件句柄。
file = io.open("main.lua", "r")    -- 使用 io.open() 函数,以只读模式打开文件
for line in file:lines() do         -- 使用 file:lines() 函数逐行读取文件
    print(line)
end
file:close()

file = io.open("main.lua", "a")  -- 使用 io.open() 函数,以添加模式打开文件
file:write("\nprint(\"hello world\")")       -- 使用 file:write() 函数,在文件末尾追加内容
file:close()

输出

Beijing
Beijing
nil
12345
360
表的长度:3
表的长度:4
表的长度:4
black
corp:12345
corp:10086
corp:100191
corp:Shanghai
表连接结果:10086123333
表最大长度:10
表删除的元素:Shanghai
表最大长度:10
表的长度:3
表删除的元素:100191
表的长度:2
排序后的表1	2	4	5	7
排序后的表7	5	4	2	1
13
字符串截取1234
字符串ID:1234
97	98	99
字符串ASCII值:97
`ab
9
1	2
nil
nil
6	7
1	3	abc
nil
lua
lua
nil
27/7/2015
hello
world
from
Lua
HelloWorld
01
hehe2333
Hello-World!
nil
123-world-1.210
nil
110
nil
100
100
0
true
false
Just so so
15
nil
index[5] have right value[18]
10
11
12
13
14
15
16
17
18
19
20
1
2
3
4
5
1
4
7
10
10
9
8
7
6
5
4
3
2
1
index:	1	value:	a
index:	2	value:	b
index:	3	value:	c
index:	4	value:	d
k:	Thursday	 v:	4
k:	Monday	 v:	1
k:	Sunday	 v:	7
k:	Wednesday	 v:	3
k:	Saturday	 v:	6
k:	Friday	 v:	5
k:	Tuesday	 v:	2
1	yes continue
i'm end
2	yes continue
i'm end
3	 no continue
i'm end
5
in the function foo0
in the function foo1
1
0
key2=val2
key1=val1
1	2	3
函数返回值:1	2	nil
函数返回值:2	1	lua
函数返回值:1	2
函数返回值:2	1	lua
函数返回值:2	1
6
总共传入4个数
6
runnoob
12
run	1	2
targetId	111
a	b	c	d
b	c	d
这是一个常量
这是一个公有函数!
这是一个私有函数!
2
1
1
111
222
lua
0
----需要调用函数,否则全局变量d没有值--
lua
444
返回当前时间:1596702865
08/06/2016:34:25
时间差为:86400
0.042055841965104
52
206
182
0.24635172087908
45
265
---
--- Generated by EmmyLua(https://github.com/EmmyLua)
--- Created by chaosye.
--- DateTime: 2020/8/5 10:48
---


print("hello world")
print("hello world")
print("hello world")
print("hello world")
print("hello world")
---
--- Generated by EmmyLua(https://github.com/EmmyLua)
--- Created by chaosye.
--- DateTime: 2020/8/5 10:48
---


print("hello world")
print("hello world")
print("hello world")
print("hello world")
print("hello world")
print("hello world")

module.lua

module = {}

-- 定义一个常量
module.constant = "这是一个常量"

-- 定义一个函数
function module.func1()
    io.write("这是一个公有函数!\n")
end

local function func2()
    print("这是一个私有函数!")
end

function module.func3()
    func2()
end

return module
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值