初识lua
转自:http://www.oschina.net/question/12_115993
-- 两个横线是单行注释(译者注:这跟 SQL 一样) --[[
增加两个 [ 和 ] 变成多行注释
我是多行注释:)
--]] ----------------------------------------------------
-- 1. 变量和程序流程控制 Variables and flow control.
---------------------------------------------------- num = 42 -- 所有的数值都是双精度的
-- 别吓一跳,64位的双精度需要52位
-- 存储,特别是 int 值,机器精度对小于 52 位的 ints 不是一个问题 s = 'walternate' -- 字符串常量,跟 Python 差不多
t = "也可以用双引号"
u = [[ 在开始和结束位置两个中括号
表示多行字符串]]
t = nil -- t 赋值为空,Lua 会进行垃圾收集 -- 块使用关键字如 do/end 来表示:
while num < 50 do
num = num + 1 -- Lua 没有 ++ 和 += 这样的操作符
end -- If 语句:
if num > 40 then
print('over 40')
elseif s ~= 'walternate' then -- ~= 是不等于的意思
-- == 是相等检查,类似 Python 和 Java; ok for strs.
io.write('not over 40\n') -- 默认写到标准输出
else
-- 变量默认是全局的
thisIsGlobal = 5 -- 常见的驼峰式大小写 -- 如何定义局部变量
local line = io.read() -- 读入标准输入下一行 -- 使用 .. 操作符进行字符串连接
print('Winter is coming, ' .. line)
end -- 未定义的变量返回 nil
-- 这不是一个错误
foo = anUnknownVariable -- 现在 foo 的值为 nil aBoolValue = false -- 只有 nil 和 false 为假,'' 为真
if not aBoolValue then print('twas false') end -- 'or' 和 'and' are short-circuited.
-- 这个类似 C/Java/JavaScript 里的 a?b:c 操作符
ans = aBoolValue and 'yes' or 'no' --> 'no' karlSum = 0
for i = 1, 100 do -- 范围包括两端的值
karlSum = karlSum + i
end -- 使用 "100, 1, -1" 进行数值递减
fredSum = 0
for j = 100, 1, -1 do fredSum = fredSum + j end -- 一般情况下,范围是 begin, end[, step]. -- 另外一种循环的方式
repeat
print('the way of the future')
num = num - 1
until num == 0 ----------------------------------------------------
-- 2. 函数.
---------------------------------------------------- function fib(n)
if n < 2 then return 1 end
return fib(n - 2) + fib(n - 1)
end -- 闭包和匿名函数
function adder(x)
-- adder 被调用时才会创建返回函数,记住 x 的值
return function (y) return x + y end
end
a1 = adder(9)
a2 = adder(36)
print(a1(16)) --> 25
print(a2(64)) --> 100 -- 返回, 函数调用和赋值都可以工作
-- 列表可能不匹配长度
-- 无法匹配的接收者就是 nil
-- 无法匹配的发送者被丢弃 x, y, z = 1, 2, 3, 4
-- 现在 x = 1, y = 2, z = 3, 和 4 被丢弃 function bar(a, b, c)
print(a, b, c)
return 4, 8, 15, 16, 23, 42
end x, y = bar('zaphod') --> 打印 "zaphod nil nil"
-- 现在 x = 4, y = 8, 而 15..42 被丢弃 -- 函数可以是全局的也可以是局部的
-- 下面是相同的
function f(x) return x * x end
f = function (x) return x * x end -- 局部函数
local function g(x) return math.sin(x) end
local g = function (x) return math.sin(x) end -- Trig funcs work in radians, by the way. -- 调用一个字符串参数无需括号
print 'hello' -- Works fine. ----------------------------------------------------
-- 3. Tables.
---------------------------------------------------- -- Tables = Lua's only compound data structure;
-- they are associative arrays.
-- Similar to php arrays or js objects, they are
-- hash-lookup dicts that can also be used as lists. -- Using tables as dictionaries / maps: -- Dict literals have string keys by default:
t = {key1 = 'value1', key2 = false} -- String keys can use js-like dot notation:
print(t.key1) -- Prints 'value1'.
t.newKey = {} -- Adds a new key/value pair.
t.key2 = nil -- Removes key2 from the table. -- Literal notation for any (non-nil) value as key:
u = {['@!#'] = 'qbert', [{}] = 1729, [6.28] = 'tau'}
print(u[6.28]) -- prints "tau" -- Key matching is basically by value for numbers
-- and strings, but by identity for tables.
a = u['@!#'] -- Now a = 'qbert'.
b = u[{}] -- We might expect 1729, but it's nil:
-- b = nil since the lookup fails. It fails
-- because the key we used is not the same object
-- as the one used to store the original value. So
-- strings & numbers are more portable keys. -- A one-table-param function call needs no parens:
function h(x) print(x.key1) end
h{key1 = 'Sonmi~451'} -- Prints 'Sonmi~451'. for key, val in pairs(u) do -- Table iteration.
print(key, val)
end -- _G is a special table of all globals.
print(_G['_G'] == _G) -- Prints 'true'. -- Using tables as lists / arrays: -- List literals implicitly set up int keys:
v = {'value1', 'value2', 1.21, 'gigawatts'}
for i = 1, #v do -- #v is the size of v for lists.
print(v[i]) -- Indices start at 1 !! SO CRAZY!
end
-- A 'list' is not a real type. v is just a table
-- with consecutive integer keys, treated as a list. ----------------------------------------------------
-- 3.1 Metatables and metamethods.
---------------------------------------------------- -- A table can have a metatable that gives the table
-- operator-overloadish behavior. Later we'll see
-- how metatables support js-prototypey behavior. f1 = {a = 1, b = 2} -- Represents the fraction a/b.
f2 = {a = 2, b = 3} -- This would fail:
-- s = f1 + f2 metafraction = {}
function metafraction.__add(f1, f2)
sum = {}
sum.b = f1.b * f2.b
sum.a = f1.a * f2.b + f2.a * f1.b
return sum
end setmetatable(f1, metafraction)
setmetatable(f2, metafraction) s = f1 + f2 -- call __add(f1, f2) on f1's metatable -- f1, f2 have no key for their metatable, unlike
-- prototypes in js, so you must retrieve it as in
-- getmetatable(f1). The metatable is a normal table
-- with keys that Lua knows about, like __add. -- But the next line fails since s has no metatable:
-- t = s + s
-- Class-like patterns given below would fix this. -- An __index on a metatable overloads dot lookups:
defaultFavs = {animal = 'gru', food = 'donuts'}
myFavs = {food = 'pizza'}
setmetatable(myFavs, {__index = defaultFavs})
eatenBy = myFavs.animal -- works! thanks, metatable -- Direct table lookups that fail will retry using
-- the metatable's __index value, and this recurses. -- An __index value can also be a function(tbl, key)
-- for more customized lookups. -- Values of __index,add, .. are called metamethods.
-- Full list. Here a is a table with the metamethod. -- __add(a, b) for a + b
-- __sub(a, b) for a - b
-- __mul(a, b) for a * b
-- __div(a, b) for a / b
-- __mod(a, b) for a % b
-- __pow(a, b) for a ^ b
-- __unm(a) for -a
-- __concat(a, b) for a .. b
-- __len(a) for #a
-- __eq(a, b) for a == b
-- __lt(a, b) for a < b
-- __le(a, b) for a <= b
-- __index(a, b) <fn or a table> for a.b
-- __newindex(a, b, c) for a.b = c
-- __call(a, ...) for a(...) ----------------------------------------------------
-- 3.2 Class-like tables and inheritance.
---------------------------------------------------- -- Classes aren't built in; there are different ways
-- to make them using tables and metatables. -- Explanation for this example is below it. Dog = {} -- 1. function Dog:new() -- 2.
newObj = {sound = 'woof'} -- 3.
self.__index = self -- 4.
return setmetatable(newObj, self) -- 5.
end function Dog:makeSound() -- 6.
print('I say ' .. self.sound)
end mrDog = Dog:new() -- 7.
mrDog:makeSound() -- 'I say woof' -- 8. -- 1. Dog acts like a class; it's really a table.
-- 2. function tablename:fn(...) is the same as
-- function tablename.fn(self, ...)
-- The : just adds a first arg called self.
-- Read 7 & 8 below for how self gets its value.
-- 3. newObj will be an instance of class Dog.
-- 4. self = the class being instantiated. Often
-- self = Dog, but inheritance can change it.
-- newObj gets self's functions when we set both
-- newObj's metatable and self's __index to self.
-- 5. Reminder: setmetatable returns its first arg.
-- 6. The : works as in 2, but this time we expect
-- self to be an instance instead of a class.
-- 7. Same as Dog.new(Dog), so self = Dog in new().
-- 8. Same as mrDog.makeSound(mrDog); self = mrDog. ---------------------------------------------------- -- Inheritance example: LoudDog = Dog:new() -- 1. function LoudDog:makeSound()
s = self.sound .. ' ' -- 2.
print(s .. s .. s)
end seymour = LoudDog:new() -- 3.
seymour:makeSound() -- 'woof woof woof' -- 4. -- 1. LoudDog gets Dog's methods and variables.
-- 2. self has a 'sound' key from new(), see 3.
-- 3. Same as LoudDog.new(LoudDog), and converted to
-- Dog.new(LoudDog) as LoudDog has no 'new' key,
-- but does have __index = Dog on its metatable.
-- Result: seymour's metatable is LoudDog, and
-- LoudDog.__index = LoudDog. So seymour.key will
-- = seymour.key, LoudDog.key, Dog.key, whichever
-- table is the first with the given key.
-- 4. The 'makeSound' key is found in LoudDog; this
-- is the same as LoudDog.makeSound(seymour). -- If needed, a subclass's new() is like the base's:
function LoudDog:new()
newObj = {}
-- set up newObj
self.__index = self
return setmetatable(newObj, self)
end ----------------------------------------------------
-- 4. Modules.
---------------------------------------------------- --[[ I'm commenting out this section so the rest of
-- this script remains runnable. -- Suppose the file mod.lua looks like this:
local M = {} local function sayMyName()
print('Hrunkner')
end function M.sayHello()
print('Why hello there')
sayMyName()
end return M -- Another file can use mod.lua's functionality:
local mod = require('mod') -- Run the file mod.lua. -- require is the standard way to include modules.
-- require acts like: (if not cached; see below)
local mod = (function ()
<contents of mod.lua>
end)()
-- It's like mod.lua is a function body, so that
-- locals inside mod.lua are invisible outside it. -- This works because mod here = M in mod.lua:
mod.sayHello() -- Says hello to Hrunkner. -- This is wrong; sayMyName only exists in mod.lua:
mod.sayMyName() -- error -- require's return values are cached so a file is
-- run at most once, even when require'd many times. -- Suppose mod2.lua contains "print('Hi!')".
local a = require('mod2') -- Prints Hi!
local b = require('mod2') -- Doesn't print; a=b. -- dofile is like require without caching:
dofile('mod2') --> Hi!
dofile('mod2') --> Hi! (runs again, unlike require) -- loadfile loads a lua file but doesn't run it yet.
f = loadfile('mod2') -- Calling f() runs mod2.lua. -- loadstring is loadfile for strings.
g = loadstring('print(343)') -- Returns a function.
g() -- Prints out 343; nothing printed before now. --]] ----------------------------------------------------
-- 5. References.
---------------------------------------------------- --[[ I was excited to learn Lua so I could make games
with the Löve 2D game engine. That's the why. I started with BlackBulletIV's Lua for programmers.
Next I read the official Programming in Lua book.
That's the how. It might be helpful to check out the Lua short
reference on lua-users.org. The main topics not covered are standard libraries:
* string library
* table library
* math library
* io library
* os library By the way, this entire file is valid Lua; save it
as learn.lua and run it with "lua learn.lua" ! This was first written for tylerneylon.com, and is
also available as a github gist. Have fun with Lua! --]]
初识lua的更多相关文章
- 【搬运工】——初识Lua(转)
使用 Lua 编写可嵌入式脚本 Lua 提供了高级抽象,却又没失去与硬件的关联. 虽然编译性编程语言和脚本语言各自具有自己独特的优点,但是如果我们使用这两种类型的语言来编写大型的应用程序会是什么样子呢 ...
- Python导出Excel为Lua/Json/Xml实例教程(一):初识Python
Python导出Excel为Lua/Json/Xml实例教程(一):初识Python 相关链接: Python导出Excel为Lua/Json/Xml实例教程(一):初识Python Python导出 ...
- Lua中模块初识
定义了两个文件: Module.lua 和 main.lua 其中,模块的概念,使得Lua工程有了程序主入口的概念,其中main.lua就是用来充当程序主入口的. 工程截图如下: Module.lua ...
- lua的函数初识
学习到Lua的函数.认为有必要记下来. 參考教程:Programming in Lua 函数能够以表达式或陈述语句出现,例如以下所看到的: print(8*9, 9/8) a = math.sin(3 ...
- openresty(nginx+lua)初识
1.新增项目配置文件: vim /usr/example/example1.conf --将以下内容加入example1.conf server { listen 80; server_name _; ...
- Python导出Excel为Lua/Json/Xml实例教程(三):终极需求
相关链接: Python导出Excel为Lua/Json/Xml实例教程(一):初识Python Python导出Excel为Lua/Json/Xml实例教程(二):xlrd初体验 Python导出E ...
- Python导出Excel为Lua/Json/Xml实例教程(二):xlrd初体验
Python导出Excel为Lua/Json/Xml实例教程(二):xlrd初体验 相关链接: Python导出Excel为Lua/Json/Xml实例教程(一):初识Python Python导出E ...
- Redis初识、设计思想与一些学习资源推荐
一.Redis简介 1.什么是Redis Redis 是一个开源的使用ANSI C 语言编写.支持网络.可基于内存亦可持久化的日志型.Key-Value 数据库,并提供多种语言的API.从2010 年 ...
- Redis——学习之路二(初识redis服务器命令)
上一章我们已经知道了如果启动redis服务器,现在我们来学习一下,以及如何用客户端连接服务器.接下来我们来学习一下查看操作服务器的命令. 服务器命令: 1.info——当前redis服务器信息 s ...
随机推荐
- java 关键字 transient
一个对象实现了Serilizable 接口,该对象就可以被序列化. 然而在实际开发工程中,我们会遇到,这个类的有些属性不需要序列化,比如包含用户的敏感信息(如密码),为了安全起见,不希望在网络操作(主 ...
- 22.Android之ExpandableListView树形列表学习
Android经常用到树形菜单,一般ExpandableListView可以满足这个需要,今天学习下. XML代码: <?xml version="1.0" encoding ...
- Bzoj 1336&1337 Alien最小圆覆盖
1336: [Balkan2002]Alien最小圆覆盖 Time Limit: 1 Sec Memory Limit: 162 MBSec Special Judge Submit: 1473 ...
- android HDMI 清晰度 分辨率
但改变分辨率时,发送广播即可: Intent intent_outputmode_change = new Intent(ACTION_OUTPUTMODE_CHANGE); intent_o ...
- Ubuntu系统启动过程详解
作者:杨硕,华清远见嵌入式学院讲师. 一. Ubuntu的启动流程 ubuntu的启动流程和我们熟知的RedHat的启动方式有所区别. RedHat的启动过程如下图: 这是我们熟知的linux启动流程 ...
- Laravel5.1 启动详解
借鉴: Laravel所有请求的入口文件是:/public/index.php,代码如下 <?php /*|------------------------------------------- ...
- IOS基础之 (十) 内存管理
一 基本原理 1.什么是内存管理 移动设备的内存有限,每个app所能占用的内存是有限制的. 当app所占用的内存较多时,系统会发出内存警告,这时得回收一些不需要再使用的内存空间.比如回收一些不需要使用 ...
- [工作积累] Google/Amazon平台的各种坑
所谓坑, 就是文档中没有标明的特别需要处理的细节, 工作中会被无故的卡住各种令人恼火的问题. 包括系统级的bug和没有文档化的限制. 继Android的各种坑后, 现在做Amazon平台, 遇到的坑很 ...
- Ubuntu 中软件的安装、卸载以及查看的方法总结
Ubuntu 中软件的安装.卸载以及查看的方法总结 博客分类: Linux UbuntuDebian配置管理CacheF# 说明:由于图形化界面方法(如Add/Remove... 和Synaptic ...
- R语言操作数据库
以下内容出自http://www.douban.com/note/172387172/ CRAN上有很多R的数据库支持包,使R能够对数据库进行读写操作.这些包有:RODBC.DBI.RMySQL.RO ...