Lua 笔记
lua命令:
#enter shell
lua
#excute script file
lua xxx.lua
lua脚本:
#!/usr/local/bin/lua
核心概念:
As a extension language, Lua has no notion of a 'Main’ program: it only works embedded in a host client, called the embedding program or simply the host. The host program can invoke functions to execute a piece of Lua code, can write and read Lua variables, and can register C functions to be called by Lua code.
Lua distrubition includes a sample host program called lua, which uses the Lua library to offer a complete, standalone Lua interpreter, for interactive or batch use.
Lua is a dynamically typed language. This means that variables do not have types; only values do. There are no type definitions in the language. All values carry their own type.
Lua can call functions written in Lua and functions written in C. Both are represented by the type function.
特性:
轻量级
可配置,可扩展
兼容性
类C的语言,大小写敏感
在Lua中,一切都是变 量,除了关键字
特点:
- 变量名没有类型,值才有类型,变量名在运行时可与任何类型的值绑定。
- 语言只提供唯一一种数据结构,称为表(Table),它混合了数组、哈希,可以用任何类型的值作为key和value;提供了一致且富有表达力的表构造语法,使得Lua很适合描述复杂的数据。
- 函数是一等类型,支持匿名函数和正则尾递归(proper tail recursion)。
- 支持词法界定(lexical scoping)和闭包(closure)。
- 提供thread类型和结构化的协程(coroutine)机制,在此基础上可方便实现协作式多任务。
- 运行期能编译字符串形式的程序文本并载入虚拟机执行。
- 通过元表(meta-table)和元方法(meta-method)提供的动态元机制(dynamic meta-mechanism),从而允许程序运行时根据需要改变或扩充语法设施的内定语义。
- 能方便地利用表和动态元机制实现基于原型(prototype-based)的面向对象模型。
- 从5.1版开始提供了完善的模块机制,从而更好地支持开发大型的应用程序。
注释:
单行:--
多行:--[[ ]]
关键字:
and break do else elseif end false for function if in local nil not or repeat return then true until while
元表与元方法:
Every value in Lua can have a metetable. This meatball is an ordinary Lua table that define the behavior of the original value under certain special operations. You can change several aspects of the behavior of operations over a value by setting specific fields in its metatable. The keys in a meatball are derived from the event names; the corresponding values are called metamethods.
You can query the metatable of any value using the getmetatable function. You can replace the metatable of tables using the setmetatable function. You can not change the metatable of other types from Lua code(except by using the debug library); you must use the C API for that.
Tables and full userdata have individual metatables. Values of all other types share one single meatball per type; that is, there is one single metatable for all numbers, one for all strings, etc. By default, a value has no metatable, but the string library sets a metatable for the string type.
变量类型: type(<var-name>)
Nil Boolean Number String Function Table Thread Userdata
========================================
Nil:
nil
Number:double
例子:
num = 234
num = 0.4
num = 4.57e-3
num = 0.3e12
num = 0xef45
函数:
tostr:
tostring(123)
String:‘’ “” [[ ]]
例子:
’This is a "string".\n'
"This is a string.\n”
[[
string in line 'one'
string in line "two"
]]
[=[
string in line [[one]]
string in line [[two]]
]=]
函数:
拼接:
‘abc’..’def’
tonum:
tonumber(‘123’)
len:
print(#’12345')
Boolean:
true,false
Condition - False:
false,nil
Function:
定义:
固定参数:
function <func-name>(<args>)
……
end
变长参数:
function <func-name>(…)
local args = {…}
…...
end
限制:
在Lua 里函数定义必须在调用之前执行,这是因为Lua里的函数定义本质上是变量赋值。
function foo() …… end
====
foo = function () …… end
参数传递:
在常用基本类型中,除Table是按地址传递外, 其它都是按值传递的。
返回值:
Lua中函数可以返回多个值,如下:
定义:
function swap(a, b)
return b, a
end
使用:
a, b = 1, 2
a, b = swap(a, b)
虚变量:
当一个方法返回多个值时,有些返回值有时候用不到,要是声明很多变量来一一接收并不太合适,于是Lua提供了一个虚变量(dummy variable),以单个下划线(“_”)来命名,用它来丢弃不需要的数据,仅仅起到占位符的作用。
local start, finish = string.find(‘Hello’, ‘he’)
local start = string.find(‘Hello’, ‘he’)
local _, finish = string.find(‘Hello’, ‘he’)
函数与方法:
静态方法和函数没有区别:
func1(……)
table.static_method(……)
实例方法和静态方法的唯一区别在于实例方法的第一个参数:
table.instance_method(table, ……)
table:instance_method(……)
动态调用:
定义:
local function doAction(method, …)
local args = {…} or {}
mothed(unpack(args, 1, table.maxn(args))
end
使用:
local function run(x, y)
ngx.say(‘run’, x, y)
end
doAction(run, 1, 2)
Table:{} 关联数组
说明:
Table是关联数组,不仅可以使用整数来索引,还可以使用除了nil之外的其他值进行索引。
Lua 中的模块、包、对象,元表均是使用table来表示的。
在Lua中,数组下标从1开始计数。
例子:
T1 = {[1]=‘one’, [2]=’two’}
one = T1[1]
T1[3] = ’three’
T1[‘four’] = 4
T1.four = 4
print(T1.four)
方法:
Thread:
Userdata:
作用域:
在默认情况下,函数外的变量总被认为是全局的,除非你在前面加上”local”;函数内的变量与函数的参数默认为局部变量。局部变量的作用域为从声明位置开始到所在语句块结束或者是直到下一个同名局部变量的声明。变量的默认值均为 nil。
local a,b,c = 1,2,3 -- a,b,c都是局部变量
迭代:
迭代文件:
io.lines()
迭代Table:
pairs(<value-of-table>)
逻辑:
算数:
+ - * / ^ %
..
逻辑:
== ~= > < >= <=
and or not
分组:
()
语句分割:
在Lua中,语句之间可以用分号";"隔开,也可以用空白隔开。
结构:
if-else:
if <condition> then
……
elseif <condition> then
…….
else
…….
end
for:
for i = <start>,<end>,<step> do
……
break
end
for i, v in pairs(<value-of-table>) do
…...
end
while:
while <condition> do
……
end
until:
repeat
……
until <condition>
function:
def:
function <func-name>(<args>)
……
end
call:
<func-name>(<args>)
closure:
return:
return <value>
multiple assign:
a, b, c = 1, 2, 3
模块:
Lua 的模块是由变量、函数等已知元素组成的 table。
引用模块:
函数 require 有它自己的文件路径加载策略,它会尝试从 Lua 文件或 C 程序库中加载模块。
lua模块:app/utils.lua
local utils = require “app.utils"
创建模块:
lua模块:app/utils.lua(/path/to/folder)
module("app.utils", package.seeall)
设置搜索路径:以;为分割符
.lua - package.path - package.loadfile
package.path的默认值为LUA_PATH环境变量的值。
package.path = [[/path/to/folder/?.lua;]] .. package.path
.so - package.cpath - package.loadlib
package.cpath的默认值为LUA_CPATH环境变量的值。
互操作与嵌入:
与C语言的互操作:
在C函数中调用Lua脚本
在Lua脚本中调用C函数
在Host 程序中嵌入Lua:
Lua的官方实现完全采用ANSI C编写,能以C程序库的形式嵌入到宿主程序中。
标准库:
basic:
环境:Lua将其所有的全局变量保存在一个常规的table中,这个table称为“环境”。
_G — 全局环境表(全局变量)
_VERSION — 返回当前Lua的版本号
函数:
type (v)
print (…)
getmetatable (object)
setmetatable (table, metatable)
getfenv (f)
setfenv (f, table)
collectgarbage (opt [, arg])
require (modname)
module(modname, package.seeall)
rawlen (v)
rawequal (v1, v2)
rawget (table, index)
rawset (table, index, value)
next (table [, index])
ipairs (table)
pairs (table)
dofile (filename)
load (func [, chunkname])
loadfile ([filename])
loadstring (string [, chunkname])
pcall (f, arg1, ···)
xpcall (f, err)
select (index, ···)
tonumber (e [, base])
tostirng (e)
unpack (list [, i [, j]])
assert (v [, message])
error (message [, level])
io: (.:)
io.close
io.flush
io.input
io.lines
io.open
io.output
io.popen
io.read
io.stderr
io.stdin
io.stdout
io.tmpfile
io.type
io.write
file:close
file:flush
file:lines
file:read
file:seek
file:setvbuf
file:write
string: (.)
string.upper
string.lower
table: (.)
table.insert
table.remove
table.sort
utf8: (.)
utf8.char
utf8.len
coroutine: (.)
coroutine.create
coroutine.status
debug: (.)
debug.debug
debug.getinfo
os: (.)
os.date
os.time
os.rename
os.remove
os.execute
package: (.)
package.path
package.cpath
package.loaded
math: (.)
math.abc
math.max
math.min
math.pi
math.random
C API:
辅助库:
Lua 笔记的更多相关文章
- Lua笔记
闭包 示例一 function newCounter() return function() -- anonymous function i = i + return i end end c1 = n ...
- Lua笔记(2)
函数高级特性 像新版c++一样,lua支持lambda表达式.也就是可以在函数内部声明函数.内层的函数可以访问外一层函数的局部变量. 一个函数以及它会访问到的外层函数的变量,称为闭包.这些变量又被称为 ...
- Lua笔记(1)
今天开始学习Lua,下面把一些重点记下来: 单行注释-- ,多行注释 --[[ ....... --]] Lua中false和nil表示条件判断的假,其余的,包括空字符串,0,都表示真. Lua没 ...
- LUA笔记之表
表据说是LUA的核, 呵呵, 看例子吧, 看上去, 跟java的list很像, 又有点像json: a = {} -- create a table and store its reference i ...
- LUA笔记之字符串
LUA提供了自动数值转换, 基本上说是乱来也不为过, 就当做是不熟悉数据结构吧, 例子: print("10" + 1) --> 11 print("10 + 1& ...
- lua笔记二 赋值语句
赋值是改变一个变量的值和改变表域的最基本的方法. a = "hello" .. "world" t.n = t.n + 1 Lua可以对多个变量同时赋值,变量列 ...
- lua笔记之userdata
1.一直使用框架里封装好的c库,想着自己一点一点的写些例子,学习下,以后需要c库,可以自己写了. 下边是一个简单的userdata的例子--数组操作. newarray.c #include &quo ...
- 设计模式实例(Lua)笔记之四(Builder 模式)
1.描写叙述: 又是一个周三,快要下班了,老大突然又拉住我,喜滋滋的告诉我"牛叉公司非常惬意我们做的模型,又签订了一个合同,把奔驰.宝马的车辆模型都交给我我们公司制作了,只是这次又 ...
- 设计模式实例(Lua)笔记之五(Bridge模式)
1.描写叙述 今天我要说说我自己,梦想中的我自己,我身价过亿,有两个大公司,一个是房地产公司,一个是服装制造业,这两个公司都非常赚钱,天天帮我在累加財富,事实上是什么公司我倒是不关心,我关心的是是不是 ...
随机推荐
- css-实现元素垂直居中对齐
css-实现元素/元素内容,垂直居中对齐 一.单行内容的垂直居中(line-height:行高方法) 只考虑单行是最简单的,无论是否给容器固定高度,只要给容器设置 line-height 和 heig ...
- Linux - 查看用户登录记录
有关用户登录的信息记录在 utmp(/var/run/utmp).wtmp(/var/log/wtmp).btmp(/var/log/btmp) 和 lastlog(/var/log/lastlog) ...
- select2的基本用法
公司有个项目需要用到类似百度搜索功能的下拉框,自然想到使用select2. 先看下select2的效果图,如下: 下来简单介绍下这个控件的基本用法,主要简单介绍下远程加载数据: 1.首先引入需要的文件 ...
- myeclipse的新建severlet不见解决方法
点击myeclipse中的window菜单里面选择myeclipse java Enterprise 选项就可以恢复到默认.
- VS2013开发Windows服务项目
这篇随笔里,我将介绍如何用VS2013开发Windows服务项目,实现的功能是定时发送电子邮件. 开发环境:VS2013,SQL Server2008,采用C#语言开发 步骤一:创建Windows服务 ...
- 安装oracle 12c遇到问题
安装前步骤:更改用户账户控制设置:从不通知 出现 "SEVERE: [FATAL] [INS-30014] 无法检查指定的位置是否位于 CFS 上" 解决办法:重新设置hosts ...
- ios简单数据库运用
一.添加类 二.打开数据库 三.创表 四.插入数据 五.取出数据 一.添加类 1.在设置Linked Frameworks and Libraries 中,点加号并添加libsqlite3.0.dyl ...
- bzoj2748:[HAOI2012]音量调节
思路:刷水有益健康. #include<iostream> #include<cstdio> #include<cstring> #include<algor ...
- [cocos2d-x 2.0.4][iOS7]不能全屏问题
本篇文章由:http://www.sollyu.com/cocos2d-x-2-0-4-ios7-cannot-be-full-screen-problem/ 说明 ▼ 症状如下图 解决 打开你工程的 ...
- 九度OJ 1408 吃豆机器人 -- 动态规划
题目地址:http://ac.jobdu.com/problem.php?pid=1408 题目描述: 淘宝公司内部有许多新鲜的小玩具,例如淘宝智能机器人.小时候,大家都玩过那个吃豆子的游戏吧,这机器 ...