lua学习笔记
lua是一门轻量级的脚本语言…好像比较适合写游戏?在 太阳神三国杀 中见过很多lua脚本。 由于splash 的渲染脚本需要用lua来写,因此来学习一波。
直接上语法…看到了python和pascal的影子orz
-- Two dashes start a one-line comment.
1--[[
2 Adding two ['s and ]'s makes it a
3 multi-line comment.
4--]]
1----------------------------------------------------
2-- 1. Variables and flow control.
3----------------------------------------------------
1num = 42 -- All numbers are doubles.
2-- Don't freak out, 64-bit doubles have 52 bits for
3-- storing exact int values; machine precision is
4-- not a problem for ints that need < 52 bits.
1s = 'walternate' -- Immutable strings like Python.
2t = "double-quotes are also fine"
3u = [[ Double brackets
4 start and end
5 multi-line strings.]]
6t = nil -- Undefines t; Lua has garbage collection.
1-- Blocks are denoted with keywords like do/end:
2while num < 50 do
3 num = num + 1 -- No ++ or += type operators.
4end
1-- If clauses:
2if num > 40 then
3 print('over 40')
4elseif s ~= 'walternate' then -- ~= is not equals.
5 -- Equality check is == like Python; ok for strs.
6 io.write('not over 40\n') -- Defaults to stdout.
7else
8 -- Variables are global by default.
9 thisIsGlobal = 5 -- Camel case is common.
-- How to make a variable local:
local line = io.read() -- Reads next stdin line.
1 -- String concatenation uses the .. operator:
2 print('Winter is coming, ' .. line)
3end
1-- Undefined variables return nil.
2-- This is not an error:
3foo = anUnknownVariable -- Now foo = nil.
aBoolValue = false
-- Only nil and false are falsy; 0 and '' are true!
if not aBoolValue then print('twas false') end
1-- 'or' and 'and' are short-circuited.
2-- This is similar to the a?b:c operator in C/js:
3ans = aBoolValue and 'yes' or 'no' --> 'no'
1karlSum = 0
2for i = 1, 100 do -- The range includes both ends.
3 karlSum = karlSum + i
4end
1-- Use "100, 1, -1" as the range to count down:
2fredSum = 0
3for j = 100, 1, -1 do fredSum = fredSum + j end
-- In general, the range is begin, end[, step].
1-- Another loop construct:
2repeat
3 print('the way of the future')
4 num = num - 1
5until num == 0
1----------------------------------------------------
2-- 2. Functions.
3----------------------------------------------------
1function fib(n)
2 if n < 2 then return 1 end
3 return fib(n - 2) + fib(n - 1)
4end
1-- Closures and anonymous functions are ok:
2function adder(x)
3 -- The returned function is created when adder is
4 -- called, and remembers the value of x:
5 return function (y) return x + y end
6end
7a1 = adder(9)
8a2 = adder(36)
9print(a1(16)) --> 25
10print(a2(64)) --> 100
1-- Returns, func calls, and assignments all work
2-- with lists that may be mismatched in length.
3-- Unmatched receivers are nil;
4-- unmatched senders are discarded.
x, y, z = 1, 2, 3, 4
-- Now x = 1, y = 2, z = 3, and 4 is thrown away.
1function bar(a, b, c)
2 print(a, b, c)
3 return 4, 8, 15, 16, 23, 42
4end
x, y = bar('zaphod') --> prints "zaphod nil nil"
-- Now x = 4, y = 8, values 15..42 are discarded.
1-- Functions are first-class, may be local/global.
2-- These are the same:
3function f(x) return x * x end
4f = function (x) return x * x end
1-- And so are these:
2local function g(x) return math.sin(x) end
3local g; g = function (x) return math.sin(x) end
4-- 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.
1----------------------------------------------------
2-- 3. Tables.
3----------------------------------------------------
1-- Tables = Lua's only compound data structure;
2-- they are associative arrays.
3-- Similar to php arrays or js objects, they are
4-- 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}
1-- String keys can use js-like dot notation:
2print(t.key1) -- Prints 'value1'.
3t.newKey = {} -- Adds a new key/value pair.
4t.key2 = nil -- Removes key2 from the table.
1-- Literal notation for any (non-nil) value as key:
2u = {['@!#'] = 'qbert', [{}] = 1729, [6.28] = 'tau'}
3print(u[6.28]) -- prints "tau"
1-- Key matching is basically by value for numbers
2-- and strings, but by identity for tables.
3a = u['@!#'] -- Now a = 'qbert'.
4b = u[{}] -- We might expect 1729, but it's nil:
5-- b = nil since the lookup fails. It fails
6-- because the key we used is not the same object
7-- as the one used to store the original value. So
8-- strings & numbers are more portable keys.
1-- A one-table-param function call needs no parens:
2function h(x) print(x.key1) end
3h{key1 = 'Sonmi~451'} -- Prints 'Sonmi~451'.
1for key, val in pairs(u) do -- Table iteration.
2 print(key, val)
3end
-- _G is a special table of all globals.
print(_G['_G'] == _G) -- Prints 'true'.
-- Using tables as lists / arrays:
1-- List literals implicitly set up int keys:
2v = {'value1', 'value2', 1.21, 'gigawatts'}
3for i = 1, #v do -- #v is the size of v for lists.
4 print(v[i]) -- Indices start at 1 !! SO CRAZY!
5end
6-- A 'list' is not a real type. v is just a table
7-- with consecutive integer keys, treated as a list.
1----------------------------------------------------
2-- 3.1 Metatables and metamethods.
3----------------------------------------------------
1-- A table can have a metatable that gives the table
2-- operator-overloadish behavior. Later we'll see
3-- 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
1metafraction = {}
2function metafraction.__add(f1, f2)
3 sum = {}
4 sum.b = f1.b * f2.b
5 sum.a = f1.a * f2.b + f2.a * f1.b
6 return sum
7end
setmetatable(f1, metafraction)
setmetatable(f2, metafraction)
s = f1 + f2 -- call __add(f1, f2) on f1's metatable
1-- f1, f2 have no key for their metatable, unlike
2-- prototypes in js, so you must retrieve it as in
3-- getmetatable(f1). The metatable is a normal table
4-- with keys that Lua knows about, like __add.
1-- But the next line fails since s has no metatable:
2-- t = s + s
3-- Class-like patterns given below would fix this.
1-- An __index on a metatable overloads dot lookups:
2defaultFavs = {animal = 'gru', food = 'donuts'}
3myFavs = {food = 'pizza'}
4setmetatable(myFavs, {__index = defaultFavs})
5eatenBy = 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.
1-- __add(a, b) for a + b
2-- __sub(a, b) for a - b
3-- __mul(a, b) for a * b
4-- __div(a, b) for a / b
5-- __mod(a, b) for a % b
6-- __pow(a, b) for a ^ b
7-- __unm(a) for -a
8-- __concat(a, b) for a .. b
9-- __len(a) for #a
10-- __eq(a, b) for a == b
11-- __lt(a, b) for a < b
12-- __le(a, b) for a <= b
13-- __index(a, b) <fn or a table> for a.b
14-- __newindex(a, b, c) for a.b = c
15-- __call(a, ...) for a(...)
1----------------------------------------------------
2-- 3.2 Class-like tables and inheritance.
3----------------------------------------------------
-- 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.
1function Dog:new() -- 2.
2 newObj = {sound = 'woof'} -- 3.
3 self.__index = self -- 4.
4 return setmetatable(newObj, self) -- 5.
5end
1function Dog:makeSound() -- 6.
2 print('I say ' .. self.sound)
3end
mrDog = Dog:new() -- 7.
mrDog:makeSound() -- 'I say woof' -- 8.
1-- 1. Dog acts like a class; it's really a table.
2-- 2. function tablename:fn(...) is the same as
3-- function tablename.fn(self, ...)
4-- The : just adds a first arg called self.
5-- Read 7 & 8 below for how self gets its value.
6-- 3. newObj will be an instance of class Dog.
7-- 4. self = the class being instantiated. Often
8-- self = Dog, but inheritance can change it.
9-- newObj gets self's functions when we set both
10-- newObj's metatable and self's __index to self.
11-- 5. Reminder: setmetatable returns its first arg.
12-- 6. The : works as in 2, but this time we expect
13-- self to be an instance instead of a class.
14-- 7. Same as Dog.new(Dog), so self = Dog in new().
15-- 8. Same as mrDog.makeSound(mrDog); self = mrDog.
----------------------------------------------------
-- Inheritance example:
LoudDog = Dog:new() -- 1.
1function LoudDog:makeSound()
2 s = self.sound .. ' ' -- 2.
3 print(s .. s .. s)
4end
seymour = LoudDog:new() -- 3.
seymour:makeSound() -- 'woof woof woof' -- 4.
1-- 1. LoudDog gets Dog's methods and variables.
2-- 2. self has a 'sound' key from new(), see 3.
3-- 3. Same as LoudDog.new(LoudDog), and converted to
4-- Dog.new(LoudDog) as LoudDog has no 'new' key,
5-- but does have __index = Dog on its metatable.
6-- Result: seymour's metatable is LoudDog, and
7-- LoudDog.__index = LoudDog. So seymour.key will
8-- = seymour.key, LoudDog.key, Dog.key, whichever
9-- table is the first with the given key.
10-- 4. The 'makeSound' key is found in LoudDog; this
11-- is the same as LoudDog.makeSound(seymour).
1-- If needed, a subclass's new() is like the base's:
2function LoudDog:new()
3 newObj = {}
4 -- set up newObj
5 self.__index = self
6 return setmetatable(newObj, self)
7end
1----------------------------------------------------
2-- 4. Modules.
3----------------------------------------------------
1--[[ I'm commenting out this section so the rest of
2-- this script remains runnable.
3-- Suppose the file mod.lua looks like this:
4local M = {}
1local function sayMyName()
2 print('Hrunkner')
3end
1function M.sayHello()
2 print('Why hello there')
3 sayMyName()
4end
return M
-- Another file can use mod.lua's functionality:
local mod = require('mod') -- Run the file mod.lua.
1-- require is the standard way to include modules.
2-- require acts like: (if not cached; see below)
3local mod = (function ()
4 <contents of mod.lua>
5end)()
6-- It's like mod.lua is a function body, so that
7-- 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.
1-- Suppose mod2.lua contains "print('Hi!')".
2local a = require('mod2') -- Prints Hi!
3local b = require('mod2') -- Doesn't print; a=b.
1-- dofile is like require without caching:
2dofile('mod2.lua') --> Hi!
3dofile('mod2.lua') --> Hi! (runs it again)
-- loadfile loads a lua file but doesn't run it yet.
f = loadfile('mod2.lua') -- Call f() to run it.
1-- loadstring is loadfile for strings.
2g = loadstring('print(343)') -- Returns a function.
3g() -- Prints out 343; nothing printed before now.
--]]
1----------------------------------------------------
2-- 5. References.
3----------------------------------------------------
--[[
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. It's
also available as a github gist. Tutorials for other
languages, in the same style as this one, are here:
http://learnxinyminutes.com/
Have fun with Lua!
--]]