15分钟入门lua
目录:[ - ]
-- 1. Variables and flow control.
-- 2. Functions.
-- 3. Tables.
-- 3.1 Metatables and metamethods.
-- 3.2 Class-like tables and inheritance.
-- 4. Modules.
-- 5. References.
原文地址:http://tylerneylon.com/a/learn-lua/
先粘下来,英文不难,回头再看,怕以后找不到或者想不起来了,囧
Learn Lua in 15 Minutes more or less -- Two dashes start a one-line comment.
--[[ Adding two ['s and ]'s makes it a multi-line comment. --]]
-- 1. Variables and flow control.
num = 42 -- All numbers are doubles. -- Don't freak out, 64-bit doubles have 52 bits for -- storing exact int values; machine precision is -- not a problem for ints that need < 52 bits.
s = 'walternate' -- Immutable strings like Python. t = "double-quotes are also fine" u = [[ Double brackets start and end multi-line strings.]] t = nil -- Undefines t; Lua has garbage collection.
-- Blocks are denoted with keywords like do/end: while num < 50 do num = num + 1 -- No ++ or += type operators. end
-- If clauses: if num > 40 then print('over 40') elseif s ~= 'walternate' then -- ~= is not equals. -- Equality check is == like Python; ok for strs. io.write('not over 40\n') -- Defaults to stdout. else -- Variables are global by default. thisIsGlobal = 5 -- Camel case is common.
-- How to make a variable local: local line = io.read() -- Reads next stdin line.
-- String concatenation uses the .. operator: print('Winter is coming, ' .. line) end
-- Undefined variables return nil. -- This is not an error: foo = anUnknownVariable -- Now foo = nil.
aBoolValue = false
-- Only nil and false are falsy; 0 and '' are true! if not aBoolValue then print('twas false') end
-- 'or' and 'and' are short-circuited. -- This is similar to the a?b:c operator in C/js: ans = aBoolValue and 'yes' or 'no' --> 'no'
karlSum = 0 for i = 1, 100 do -- The range includes both ends. karlSum = karlSum + i end
-- Use "100, 1, -1" as the range to count down: fredSum = 0 for j = 100, 1, -1 do fredSum = fredSum + j end
-- In general, the range is begin, end[, step].
-- Another loop construct: repeat print('the way of the future') num = num - 1 until num == 0
-- 2. Functions.
function fib(n) if n < 2 then return 1 end return fib(n - 2) + fib(n - 1) end
-- Closures and anonymous functions are ok: function adder(x) -- The returned function is created when adder is -- called, and remembers the value of x: return function (y) return x + y end end a1 = adder(9) a2 = adder(36) print(a1(16)) --> 25 print(a2(64)) --> 100
-- Returns, func calls, and assignments all work -- with lists that may be mismatched in length. -- Unmatched receivers are nil; -- unmatched senders are discarded.
x, y, z = 1, 2, 3, 4 -- Now x = 1, y = 2, z = 3, and 4 is thrown away.
function bar(a, b, c) print(a, b, c) return 4, 8, 15, 16, 23, 42 end
x, y = bar('zaphod') --> prints "zaphod nil nil" -- Now x = 4, y = 8, values 15..42 are discarded.
-- Functions are first-class, may be local/global. -- These are the same: function f(x) return x * x end f = function (x) return x * x end
-- And so are these: local function g(x) return math.sin(x) end local g; g = function (x) return math.sin(x) end -- the 'local g' decl makes g-self-references ok.
-- Trig funcs work in radians, by the way.
-- Calls with one string param don't need parens: 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) 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 () 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!
--]]
15分钟入门lua的更多相关文章
- 15分钟学会Lua
lua的很多语法跟matlab很像 最基本的赋值是一样的 循环和选择判断后面必须跟一个关键字:do和then ,, do ... end if - then - end table是lua的唯一一种数 ...
- 15分钟入门Markdown
一.标题一 标题三 标题六 # 一.标题一 ### 标题三 ###### 标题六 二.字体 1.普通字体 字体加粗 斜体 斜体加粗 删除线 1.普通字体 **字体加粗** *斜体* ***斜体加粗** ...
- iOS开发60分钟入门
原文:https://github.com/qinjx/30min_guides/blob/master/ios.md 本文面向已有其它语言(如Java,C,PHP,Javascript)编程经验的i ...
- 正则表达式30分钟入门教程<转载>
来园子之前写的一篇正则表达式教程,部分翻译自codeproject的The 30 Minute Regex Tutorial. 由于评论里有过长的URL,所以本页排版比较混乱,推荐你到原处查看,看完了 ...
- Python 30分钟入门指南
Python 30分钟入门指南 为什么 OIer 要学 Python? Python 语言特性简洁明了,使用 Python 写测试数据生成器和对拍器,比编写 C++ 事半功倍. Python 学习成本 ...
- 15 分钟学会 Eclipse GMF
背景 坦白说:过去在 Eclipse 里使用 Graphical Editor Framework(GEF)创建图形化编辑器 既慢又痛苦.这个过程包括理解复杂的框架和大量的冗余代码.但也说明 GEF ...
- 15分钟学会使用Git
http://blog.csdn.net/u013510614/article/details/50588446 主体思想 Git作为一个复杂的版本控制系统,命令之多,相信很多小白已经望而却步,有的尝 ...
- 15分钟带你了解前端工程师必知的javascript设计模式(附详细思维导图和源码)
15分钟带你了解前端工程师必知的javascript设计模式(附详细思维导图和源码) 前言 设计模式是一个程序员进阶高级的必备技巧,也是评判一个工程师工作经验和能力的试金石.设计模式是程序员多年工作经 ...
- top,它们的意思分别是1分钟、5分钟、15分钟内系统的平均负荷。
理解Linux系统负荷 作者: 阮一峰 日期: 2011年7月31日 一.查看系统负荷 如果你的电脑很慢,你或许想查看一下,它的工作量是否太大了. 在Linux系统中,我们一般使用uptime ...
随机推荐
- 利用keyframes实现幻灯效果
源码如下: <style> @keyframes looppic{ from{ background:url(images/1.jpg); /*图片的地址*/ } 25%{ /*可以依据不 ...
- 浅谈CDN加速问题
(以百度CDN进行分析) 婆说婆有理,公说公有理.是否使用CDN,不同的工程师有不同的意见. 这里呢我来进行一下简单的分析. [正方观点] 1. 提升网站加载速度:CDN通过缓存技术提升网站打开速度, ...
- HZNU_TI1050 训练实录
菜鸡队训练实录 比赛记录:[名称:奖项 / 排名] 2018: ZJPSC Bronze / 86 CCPC Jilin ...
- ES6之前模拟Map数据结构的写法
在ES6之前JavaScript 里面本身没有map对象,但是用JavaScript的Array.Object来模拟实现Map的数据结构. 现在已经有Map对象了,这里记录一下之前的写法 Array方 ...
- SNMP学习笔记之SNMP简单概述
0x00 SNMP简单概述 0.1.什么是Snmp SNMP是英文"Simple Network Management Protocol"的缩写,中文意思是"简单网络管理 ...
- Intel RDT
首先 spec, 从671页看起 https://software.intel.com/sites/default/files/managed/a4/60/325384-sdm-vol-3abcd.p ...
- zabbix监控之自定义item
zabbix安装完成后,当需要使用自定义脚本构建自定义item必须注意以下几点: 1.首先使用zabbix_get手动在zabbix-server服务端获取监控的默认的item值,如下: [root@ ...
- 20145317彭垚_Web基础
20145317彭垚_Web基础 基础知识 Apache一个开放源码的网页服务器,可以在大多数计算机操作系统中运行,由于其多平台和安全性被广泛使用,是最流行的Web服务器端软件之一.它快速.可靠并且可 ...
- [noip模拟题]排队
[问题描述] 小sin所在的班有n名同学,正准备排成一列纵队,但他们不想按身高从矮到高排,那样太单调,太没个性.他们希望恰好有k对同学是高的在前,矮的在后,其余都是矮的在前,高的在后.如当n=5,k= ...
- linux平台关闭某个进程的脚本
在开发LINUX平台下的程序时,经常需要为我们的开发的程序写启动程序和关闭程序的脚本. 启动脚本比较好做,关闭程序脚本如下: 具体思路是通过ps命令找到程序的进程ID号,然后通过Kill命令将程序Ki ...