Luau 与 Swift 对照
同一个程序分别用 Luau 和 Swift 编写,取自本课程的课时。
绑定与可变性
Luau 表变量保存的是引用。局部声明或数组类型注解不会冻结表,通过别名调用 table.clear 会清空同一个底层对象。静态注解会限制经过检查的操作,而 table.freeze 是单独的运行时操作,并且是浅冻结。
Luau1local pending: {string} = {"upload", "index"}2local alias = pending3table.clear(alias)4print(tostring(#pending) .. " " .. tostring(#alias))Swift1import Foundation2let pending = ["upload", "index"]3var copy = pending4copy.removeAll()5print(pending.count, copy.count)字符串与插值
Luau 反引号插值会求值大括号内部的表达式。字符串依然是字节序列,下面的前缀检查在 ASCII 路径上使用字节位置。string.rep 用于重复字符串;插值和重复都不会改变所得文本的索引单位。
Luau1local folder = "cache"2local path = `{folder}/image`3print(path:sub(1, 6) == "cache/")4print(string.rep(".", 3))Swift1import Foundation2let folder = "cache"3let path = "\(folder)/image"4print(path.hasPrefix("cache/"))5print(String(repeating: ".", count: 3))Switch 与模式
Luau 使用按顺序排列的 if 检查,而不是内置的 switch 或元组模式语法。该函数在处理更广泛的垂直情况之前,先处理更具体的原点情况。颠倒这些检查将对原点进行不同的分类,因此分支顺序也是程序行为的一部分。
Luau1local function axis(x: number, y: number): string2 if x == 0 and y == 0 then return "origin" end3 if x == 0 then return "vertical" end4 return "other"5end6print(axis(0, 9))Swift1import Foundation2func axis(_ x: Int, _ y: Int) -> String {3 switch (x, y) {4 case (0, 0): return "origin"5 case (0, _): return "vertical"6 default: return "other"7 }8}函数与标签
Luau 的参数是按位置传递的。带有类型的选项表可以给字段指定一个名称,例如 prefix,但调用者仍然需要传递一个表值作为单个参数。字段契约可以进行静态检查;它与语言层面的外部参数标签不同。
Luau1local function mark(text: string, options: {prefix: string}): string2 return options.prefix .. text3end4print(mark("draft", {prefix = "!"}))Swift1import Foundation2func mark(_ text: String, with prefix: String) -> String { prefix + text }字典与缺失键
Luau 使用 table 键作为映射条目。将 nil 赋值给 cache 会将其移除,使用 pairs 可以枚举剩余的键。# 运算符是序列长度操作,而不是对字符串键的通用计数。存储的 false 即使是假值,也依然是一个条目;nil 和 false 在映射中具有不同的含义。
Luau1local flags: {[string]: boolean} = {cache = true}2flags.cache = nil3print(flags.cache or false)4local count = 05for _ in pairs(flags) do count += 1 end6print(count)Swift1import Foundation2var flags = ["cache": true]3flags["cache"] = nil4print(flags["cache"] ?? false)5print(flags.count)结构体与独立副本
Luau 记录类型描述了表的字段以进行静态检查,但并不赋予其值语义。first 和 second 仍然指向同一个表,因此通过 second 翻转其 enabled 字段的变化在 first 中同样可见。类型形状与运行时标识是互相独立的考量。
Luau1type Toggle = {enabled: boolean}2local first: Toggle = {enabled = false}3local second = first4second.enabled = not second.enabled5print(tostring(first.enabled) .. " " .. tostring(second.enabled))Swift1import Foundation2struct Toggle {3 var enabled: Bool4 mutating func flip() { enabled.toggle() }5}
课程大纲
10 章48 节课1 个项目48 个挑战99 道测验题常见问题
面向 Luau 开发者的 Swift 课程 适合谁学习?
适合已经会写 Luau、想学 Swift 的人。每节课都从你熟悉的 Luau 代码出发,展示 Swift 如何实现同样的事情,所以你可以跳过入门基础。
需要先会 Swift 吗?
不需要。课程从你的第一个 Swift 程序开始。你需要掌握 Luau 基础:变量、条件、循环、函数和集合。
面向 Luau 开发者的 Swift 课程 有多少节课?
面向 Luau 开发者的 Swift 课程 包含 48 节互动课,你可以按自己的节奏完成。
面向 Luau 开发者的 Swift 课程 包含哪些内容?
本课程分为以下几章:Swift 入门, 文本与决策, 控制流, 函数与数组, and more。
面向 Luau 开发者的 Swift 课程 免费吗?
是的。Coddy 上的每门课程都可以免费开始。你可以直接在浏览器中完成课程,无需下载,也无需注册。