-- 两个'-'作为单行注释
--[[
多行注释
多行注释
--]]
----------------------------------------------------
-- 1. 变量和控制流程
----------------------------------------------------
num = 42 -- 所有数字都是double类型
-- 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 = '单引号字符串' -- 不可变字符串
t = "双引号也行"
u = [[
多行字符串
多行字符串
]]
t = nil -- 取消声明, lua gc 会回收.
-- while ... do ... end
while num < 50 do
num = num + 1 -- 不支持 ++ 或 += 操作符
end
-- if ... then ... elseif ... then ... else ... end
if num > 40 then
print('over 40')
elseif s ~= 'walternate' then -- ~= 不等于
-- == 等于; ok for strs.
io.write('not over 40\n') -- 默认输出到stdout
else
-- 变量默认是全局的
thisIsGlobal = 5 -- 驼峰命名
-- 局部变量
local line = io.read() -- 读取写一个stdin line
-- 字符串连接, 用 ..
print('Winter is coming, ' .. line)
end
-- 未声明变量返回 nil.
-- 这不是错误
foo = anUnknownVariable -- Now foo = nil.
aBoolValue = false
-- nil 和 false 是 false; 0 和 '' 是 true
if not aBoolValue then print('it was false') end
-- 'or' 和 'and' 是短路计算的
-- 类似于C的三目运算 a ? b : c
ans = aBoolValue and 'yes' or 'no' --> 'no'
karlSum = 0
for i = 1, 100 do -- 范围是闭区间, 包括两个端点
karlSum = karlSum + i
end
-- Use "100, 1, -1" 作为范围循环倒数
fredSum = 0
for j = 100, 1, -1 do fredSum = fredSum + j end
-- 通常, 范围循环格式是 begin, end[, step].
-- 另一个循环结构, reat ... until ...
repeat
print('num: ', num)
num = num - 10
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
-- Returns, func calls, and assignments all work
-- with lists that may be mismatched in length.
-- 未匹配的接收者为nil;
-- 未匹配的发送者被丢弃.
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') --> 打印 "zaphod nil nil"
-- Now x = 4, y = 8, values 15...42 are discarded.
-- 函数是一等公民, 可以是局部/全局的.
-- 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.
-- 一个参数的函数调用,无需括号
print 'hello' -- Works fine
----------------------------------------------------
-- 3. 表
----------------------------------------------------
-- Tables = lua 里唯一的复合数据结构, 结合array
-- 类似php里的array, 可以是数组或对象
-- 使用table作为map/dict
-- 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 = {} -- 新增newKey
t.key2 = nil -- 移除key2
-- key可以是任意非 nil 类型
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[{}] -- 我们以为是 1729, 但却是 nil:
-- 因为[{}]作为key, 存储时和取用时结构不一样
-- 字符串和数字是适合的key.
-- 调用one-table-param参数的函数,无需括号
function h(x) print(x.key1) end
h{key1 = 'Sonmi~451'} -- Prints 'Sonmi~451'.
for key, val in pairs(u) do -- table遍历
print(key, val)
end
-- _G is a special table of all globals.
print(_G)
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是table的长度
print(v[i]) -- 索引从 1 开始
end
-- A 'list' is not a real type. v is just a table
-- with consecutive integer keys, treated as a list.
----------------------------------------------------
-- 3.1 元表和元方法
----------------------------------------------------
-- table 通过setmetable 获得操作符重载能力
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 -- 在f1的metatable上调用 __add(f1, f2)
print('s.a', s.a, s.b)
-- 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.
-- __index 可重载key
defaultFavs = {animal = 'gru', food = 'donuts'}
myFavs = {food = 'pizza'}
setmetatable(myFavs, {__index = defaultFavs})
print('myFavs.animal', myFavs.animal, myFavs.food)
-- 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的表和继承
----------------------------------------------------
-- 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() -- Prints: Why hello there 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.lua') --> Hi!
dofile('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.
-- load is loadfile for strings.
-- (loadstring is deprecated, use load instead)
g = load('print(343)') -- Returns a function.
g() -- Prints out 343; nothing printed before now.
--]]