#!/home/auss/Projects/Qt/annotated/lua
-- 这是第一次系统学习Lua语言
--[[
参考资料:
1. [Lua简明教程](http://coolshell.cn/articles/10739.html)
2. [Lua基础 类型和值](http://blog.csdn.net/wzzfeitian/article/details/8292130)
3. [Lua Reference Mannual](http://www.lua.org/manual/5.3/)
4. [Lua开发者](http://book.luaer.cn/)
5. [Lua手册](http://manual.luaer.cn/) Lua脚本语言,是一个便捷的,支持拓展和热更新的语言。
Lua使用C98标准编写,解释器仅仅几百kb,小的不可思议。
通过学习Lua的语法,对该语言的使用有基本的认识。
等熟练之后,尝试着阅读源码,可以学习到很多知识,毕竟这是工业级的源码。
可能会涉及到的议题:C与C指针,数据结构,设计模式,编译原理,操作系统等。 Lua 数字只有double型64bits.
默认变量的类型是global型,局部变量前需要加上local关键字声明。 Lua 的字符串支持单引号和双引号,还支持C类型的转义。
\a bell
\b back space
\f form feed
\n newline
\r carriage return
\t horizontal tab
\v vertical tab
\\ backslash
\" double quote
\' single quote C语言中的NULL在Lua中是nil,指的是未定义变量。
bool型只有nil和false是false,数字0和空字符('\0')都是true. 任何期待一个number的地方,如果传入string,都是尝试将string转换为number。相反,在一个期待string的地方,如果传入number,那么也会尝试将number转换为string。当然也可以使用tostring和tonumber想换转换。
]]-- print("Hello, Lua @\r\n2017.02.07")
print(type(3.14159e2))
print(type(print))
print(type(type))
print(type(type(123)))
print(type('Hello'))
print(type(nil))
print(type(true))
print(type(false)) a = 'one string' --字符串是常量,不可更改
b = string.gsub(a,"one","another") --创建新的string对象
print(a)
print(b) -- 关于number和string的操作
num = 10
str = "10"
print(tostring(num)==str) --显式转换
print(num==tonumber(str)) --显式转换
print(10 .. 20) -- ".."是Lua中的字符串连接符号,这里将number自动换为string
print("-5.3e-10"*"2") --自动转换为数字
print("10"+1) --自动转换为数字
print("10+1") --字符串
print(#"hello") --获取字符串长度 # -- 控制语句
print("while-do-end control flow")
sum,idx = 0, 0
while idx <= 100 do
sum = sum + idx
idx = idx + 1 --没有++或+=等重载操作符
end
print("sum of [1,2,...,100] is",sum)
print("sum of [1,2,...,100] is "..sum) -- if-else分支
print("if-then-elseif-then-else-end control flow")
sex = "Male"
print("Input age:")
age = tonumber(io.read())
if age <= 20 and sex =="Male" then
print("努力吧,骚年!")
elseif age > 25 and sex ~="Female" then
print("都成年了,还不奋斗!")
else
print("You Lady!")
end -- for控制流
sum = 0
for i=100,1,-2 do
sum = sum + i
end
print("sum of [100:-2:1] is",sum) -- repeat-until循环控制
sum = 2
repeat
sum = sum ^2 -- 幂操作
print(sum)
until sum > 1000 -- 简单函数
function foo(x) return x^3 end
foo2 = function(x) return x^3 end
print(foo(2))
print(foo2(2)) -- 递归函数
function fib(n)
if n < 2 then return 1 end
return fib(n-1)+fib(n-2)
end
print("fib(10)=",fib(10)) -- 闭包1
function myPower(x)
return function(y)
local res = y^x
return res
end
end power2 = myPower(2)
power3 = myPower(3) print(power2(4)) --4的2次方
print(power2(5)) --5的2次方
print(power3(4)) --4的3次方
print(power3(5)) --5的3次方 -- 闭包2
function newCounter()
local i = 0
return function() -- anonymous function
i = i + 1
return i
end
end cnt = newCounter()
print(cnt()) --> 1
print(cnt()) --> 2 -- 赋值和返回值
function getUserInfo(id)
print(id)
local name,age,bGay,girlfriend = "jin",24,false,nil
return name,age,bGay,girlfriend
end name,age,bGay,girlfriend,other = getUserInfo() -->没有传入id,id是nil
print(name,age,bGay,girlfriend,other) -->"jin",24,false,nil,nil -- Table是一个Key-Value键值数据结构,很像Python中的dict,C语言中的表驱动结构体,
-- C++中的map,Javascript中的Object jincc = {name="Jincc", age=25, male=True}
jincc.name = nil
jincc.website = "http://coolshell.cn"
for k,v in pairs(jincc) do
print(k,v)
end jincc = {['name']="Jincc", ['age']=24, ['male']=True}
print(jincc['name'],jincc['age'],jincc['male']) arr = {10,20,30,40,50}
arr = {[1]=10, [2]=20, [3]=30, [4]=40, [5]=50}
arr = {"string", 100, "jincc", function() print("coolshell.cn") end}
for i=1,#arr do
print(arr[i])
end -- 遍历Table(全局变量_G也是一个Table)
for k,v in pairs(arr) do
print(k,v)
end -- MetaTable 和 MetaMethod
--[[
MetaTable和MetaMethod是Lua中的重要的语法,用来做一些类似于C++重载操作符式的功能。
Lua内置的MetaMethod有:
__add(a, b) 对应表达式 a + b
__sub(a, b) 对应表达式 a - b
__mul(a, b) 对应表达式 a * b
__div(a, b) 对应表达式 a / b
__mod(a, b) 对应表达式 a % b
__pow(a, b) 对应表达式 a ^ b
__unm(a) 对应表达式 -a
__concat(a, b) 对应表达式 a .. b
__len(a) 对应表达式 #a
__eq(a, b) 对应表达式 a == b
__lt(a, b) 对应表达式 a < b
__le(a, b) 对应表达式 a <= b
__index(a, b) 对应表达式 a.b
__newindex(a, b, c) 对应表达式 a.b = c
__call(a, ...) 对应表达式 a(...) ]]-- -- 两个分数,想实现分数之间的加法操作,需要使用MetaTable和MetaMethod
fraction_a = {numerator = 4, denominator = 5}
fraction_b = {numerator = 3, denominator = 7} -- 定义MetaTable 的 MetaMethod
fraction_op = {}
function fraction_op.__add(f1,f2)
ret = {}
ret.numerator = f1.numerator * f2.denominator + f2.numerator * f1.denominator
ret.denominator = f1.denominator * f2.denominator
return ret
end
-- 设置 metatable
setmetatable(fraction_a,fraction_op)
setmetatable(fraction_b,fraction_op) -- 调用metamethod,实际上调用的是 fraction_op._add()函数
fraction_s = fraction_a + fraction_b function print_fraction(f)
print(f.numerator,f.denominator)
return nil
end
print_fraction(fraction_a)
print_fraction(fraction_b)
print_fraction(fraction_s) -- 重载find key操作(也就是__index),组合对象,类似于JavaScript的prototype
Window_Prototype = {x=0,y=0,width=1280,height=768}
MyWin={title="Hello,Lua"}
setmetatable(MyWin,{__index=Window_Prototype})
for k,v in pairs(MyWin) do
print(k,v)
end -- Lua的面向对象
Person={}
function Person:new(p)
local obj = p
if(obj == nil) then
obj = {['name']="Jincc", ['age']=24, ['male']=True}
end
self.__index = self
return setmetatable(obj,self)
end function Person:toString()
return "Person\nname: "..self['name'].."\nage:" .. self['age'].."\nmale:".. (self['male'] and "yes" or "no")
end --[[
Person有一个new方法和toString方法,其中:
1)self 就是 Person,Person:new(p),相当于Person.new(self, p)
2)new方法的self.__index = self 的意图是怕self被扩展后改写,所以,让其保持原样
3)setmetatable这个函数返回的是第一个参数的值。
]]--
-- 调用
me = Person:new()
print("===============\n",me:toString())
kf = Person:new{name="King's fucking", age=70, handsome=false}
print("===============\n",kf:toString()) -- Person的继承。Lua和JavaScript很相似,都是在MetaTable或Prototype实例上进行修改
Student = Person:new()
function Student:new()
newObj = {year = 2017}
self.__index =self
return setmetatable(newObj,self)
end
st = Student:new()
print("===============\n",st:toString()) -- 修改toString()
function Student:toString()
return "Student\nname: "..self['name'].."\nyear:"..self.year
end
st = Student:new()
print("===============\n",st:toString())

[2017.02.07] Lua入门学习记录的更多相关文章

  1. redis入门学习记录(二)

    继第一节 redis入门学习记录(一)之后,我们来学习redis的基本使用. 接下来我们看看/usr/local/redis/bin目录下的几个文件作用是什么? redis-benchmark:red ...

  2. gulp入门学习教程(入门学习记录)

    前言 最近在通过教学视频学习angularjs,其中有gulp的教学部分,对其的介绍为可以对文件进行合并,压缩,格式化,监听,测试,检查等操作时,看到前三种功能我的心理思想是,网上有很多在线压缩,在线 ...

  3. 2015年12月02日 GitHub入门学习(四)Git操作

    序,学习使用Git是一项新技能,你将了解到Git与SubVersion的区别. 一.基本操作 git init 初始化仓库,请实际建立一个目录并初始化仓库,.git目录里存储着管理当前目录内容所需的仓 ...

  4. SpringBoot入门学习记录(一)

    最近,SpringBoot.SpringCloud.Dubbo等框架非常流行,作为Coder里的一名小学生,借着改革开放的东风,自然也是需要学习学习的,于是将学习经历记录于此,以备日后查看. 官网:h ...

  5. Sentinel入门学习记录

    最近公司里面在进行微服务开发,因为有使用到限流降级,所以去调研学习了一下Sentinel,在这里做一个记录. Sentinel官方文档:https://github.com/alibaba/Senti ...

  6. lua 入门学习

    -- 1.Hello world print( "--------------1--------------") print("Hello world"); - ...

  7. 了不起的分支和循环02 - 零基础入门学习Python008

    了不起的分支和循环02 让编程改变世界 Change the world by program 上节课,小甲鱼教大家如何正确的打飞机,其要点就是:判断和循环,判断就是该是不该做某事,循环就是持续做某事 ...

  8. scikit-learn入门学习记录

    一加载示例数据集 from sklearn import datasets iris = datasets.load_iris() digits = datasets.load_digits() 数据 ...

  9. mybatis入门学习记录(一)

    过硬的技术本领,可以给我们保驾护航,飞得更高.今天开始呢.我们就一起来探讨使用mybatis的好处. 首先我们一起来先看看原生的JDBC对于数据库的操作,然后总结其中的利弊,为学习mybatis奠定基 ...

随机推荐

  1. 五、Hive

    一.Hive 1.1 Hive简介 1.2 Hive说明 1.3Hive的体系架构 来自为知笔记(Wiz)

  2. iOS开发——设备信息小结(未完待续...)

    1.获取设备的信息  UIDevice *device = [[UIDevice alloc] init]; NSString *name = device.name;       //获取设备所有者 ...

  3. IOS开发-OC学习-常用功能代码片段整理

    IOS开发-OC学习-常用功能代码片段整理 IOS开发中会频繁用到一些代码段,用来实现一些固定的功能.比如在文本框中输入完后要让键盘收回,这个需要用一个简单的让文本框失去第一响应者的身份来完成.或者是 ...

  4. lua 函数

    1.函数只有一个参数,且该参数为table 或 字符串时,调用函数可以省略() print"hello world" 同 print("hello world" ...

  5. Eclipse上Spring-tool的安装

    三种安装方式: 插件地址:http://spring.io/tools/sts/all 1.在线安装  Help-->> Install new Software 2.本地安装,Help- ...

  6. php包管理工具最基本的一些问题

    windows下的 1.先安装windows下的set-up程序 点击一步步的, cmd进入,输入composer能成功显示一幅图说明安装成功 2.在下载,https://getcomposer.or ...

  7. BZOJ1478 Sgu282 Isomorphism

    Problem A: Sgu282 Isomorphism Time Limit: 15 Sec  Memory Limit: 64 MBSubmit: 172  Solved: 88[Submit] ...

  8. ashx文件中使用session提示“未将对象引用设置到对象的实例”

    using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Data;u ...

  9. python unicode 转中文 遇到的问题 爬去网页中遇到编码的问题

    How do convert unicode escape sequences to unicode characters in a python string 爬去网页中遇到编码的问题 Python ...

  10. redis 配置(1)

    redis配置密码 1.通过配置文件进行配置yum方式安装的redis配置文件通常在/etc/redis.conf中,打开配置文件找到 #requirepass foobared 去掉行前的注释,并修 ...