Roblox = 全球最大 Lua 平台

Roblox 平台上数亿玩家、上百万开发者——绝大多数游戏脚本是 Luau 写的。Luau 是 Roblox 自家从 Lua 5.1 fork 的方言。

Luau vs 标准 Lua

Lua 5.1 / LuaJIT Luau
整数 无(双精度)
位运算 无 / bit 库 bit32 库 + 内置操作符
类型注解 (可选)
严格模式 --!strict / --!nonstrict
字符串 \u{}
continue
if-then-else 表达式
string interpolation \{name}``
标准库 Lua 5.1 大幅扩展 + 沙箱化

Luau 是 Lua 5.1 的"演化版"——加了类型系统、性能、新语法。详见 luau-lang.org

类型注解

--!strict

local function add(a: number, b: number): number
    return a + b
end

type Point = { x: number, y: number }
local p: Point = { x = 1, y = 2 }

--!strict 让 IDE 严格检查类型。--!nonstrict 是默认(宽松)。

Roblox Studio

下载 Roblox Studio(Windows / Mac)——免费。

界面:

  • Explorer:场景树(Workspace、StarterPlayer、ReplicatedStorage...)
  • Properties:选中对象的属性
  • Output:print 输出
  • Script editor:Luau 代码

第一个脚本

新建 Baseplate → Workspace 里加一个 Part → 右键 Part → Insert Object → Script

-- 加在 Part 里的 Script
local part = script.Parent

part.Touched:Connect(function(hit)
    local player = game.Players:GetPlayerFromCharacter(hit.Parent)
    if player then
        print(player.Name .. " 碰到了 part")
        part.BrickColor = BrickColor.Random()
    end
end)

按 F5 / Play——人物角色(你)碰到 Part 时 Part 变色、Output 打印用户名。

Script vs LocalScript vs ModuleScript

跑在哪 用于
Script 服务器 游戏逻辑、防作弊、跨玩家共享
LocalScript 客户端(玩家自己) UI、输入、本地特效
ModuleScript 不主动执行,被 require 共享代码、库

放置位置决定执行环境——Roblox 比标准 Lua 多一层"哪边跑"的心智。

ModuleScript 例

-- ReplicatedStorage/Utils (ModuleScript)
local Utils = {}

function Utils.distance(a, b)
    return ((a.X - b.X)^2 + (a.Y - b.Y)^2 + (a.Z - b.Z)^2)^0.5
end

return Utils
-- 任意 Script 里
local Utils = require(game.ReplicatedStorage.Utils)
print(Utils.distance(Vector3.new(0,0,0), Vector3.new(3,4,0)))   -- 5

ReplicatedStorage 里的内容客户端 / 服务器都能 require。仅服务器的代码放 ServerStorage / ServerScriptService。

RemoteEvent / RemoteFunction

客户端 ↔ 服务器通信:

-- ReplicatedStorage 里新建 RemoteEvent
local re = game.ReplicatedStorage.GiveCoinsEvent

-- 服务器端 Script
re.OnServerEvent:Connect(function(player, amount)
    print(player.Name .. " requested " .. amount .. " coins")
    -- 验证后加金币
end)

-- 客户端 LocalScript
re:FireServer(100)

安全铁律:客户端能传任何参数。服务器必须验证——不要相信 amount 是 100。

Roblox API 学习路径

  1. Roblox Creator Hub — 官方教程
  2. Roblox API Reference — 全部对象 / 方法
  3. DevForum — 高级问题
  4. Luau 文档 — 类型系统 / 性能

注意

  • Roblox 的 print 输出在 Studio Output 窗,不在终端
  • 服务器脚本里不能 os.execute——沙箱禁止
  • HTTP 调用要在 Game Settings 启用,且只能用 HttpService:GetAsync / PostAsync
  • 性能瓶颈通常在物理 / 渲染——脚本本身 Luau JIT 已经很快

→ 下一篇 Love2D 写 2D 游戏