变量

x = 10              -- 全局(不推荐)
local y = 20        -- 局部(永远首选)
local a, b, c = 1, 2, 3
local p, q = 10     -- p=10, q=nil

铁律:默认加 local。Lua 的"全局"是隐式的——少写一个 local,变量飞到全局,难追 bug。

8 种类型

type(nil)         --> "nil"
type(true)        --> "boolean"
type(42)          --> "number"
type("hi")        --> "string"
type({})          --> "table"
type(print)       --> "function"
type(io.stdin)    --> "userdata"   -- C 数据
type(coroutine.create(function() end))  --> "thread"

就这 8 种。没有 list / dict / class / array——都是 table第 06 篇 详讲)。

number

5.3 起分两个子类型:

type(1)       --> "number"
math.type(1)        --> "integer"
math.type(1.0)      --> "float"
math.type(1 / 2)    --> "float"
math.type(1 // 2)   --> "integer"   -- 整数除法

5.1 / LuaJIT 只有 float(double),整数到 2^53 不丢精度。

字符串

local s1 = "double quotes"
local s2 = 'single quotes'        -- 等价
local s3 = [[
多行
原始字符串
]]
local s4 = [==[ 长括号,里面可以含 ]] ]==]   -- = 数任意多

.. 拼接,# 取长度:

print("a" .. "b")       -- ab
print(#"hello")         -- 5

注释

-- 单行注释

--[[
多行
注释
]]

--[==[ 长括号注释 ]==]

真假

只有 nilfalse 是假——0、空字符串、空表都是真。

if 0 then print("0 是真") end           -- 打印
if "" then print("空字符串是真") end    -- 打印
if {} then print("空表是真") end        -- 打印

这与 Python / JS 完全不同。别移植直觉

运算符

+   -   *   /     -- 加减乘除(除法总返回 float)
//                -- 整数除法(5.3+)
%                 -- 取模
^                 -- 幂
..                -- 字符串拼接
==   ~=           -- 等 / 不等(不是 !=)
<    >   <=   >=  -- 比较
and  or  not      -- 逻辑(关键字,不是 && || !)
#                 -- 长度(字符串 / 数组)
&  |  ~  <<  >>   -- 位运算(5.3+)

注意 ~= 不等(不是 !=),and / or 是关键字。

短路求值

local name = user_name or "anonymous"   -- user_name 为 nil 时用默认值
local valid = obj and obj.valid          -- nil-safe 访问

a or b:a 为真返回 a,否则返回 b。常用作"默认值"和"安全访问"。

分号

可选。一行多语句时分隔用:

local x = 1; local y = 2

99% 时候不写。

例:第一个像样的程序

local function greet(name)
    name = name or "world"
    print("Hello, " .. name .. "!")
end

greet()           -- Hello, world!
greet("Lua")      -- Hello, Lua!

→ 下一篇 字符串