Luau入門9:エラーで止まらないようにする(pcall)
初級Luau更新日:2026年11月13日Luauの型チェック済み
ひとことで言うと
データの保存のように失敗することがある処理は、pcall で包むと、エラーが起きてもスクリプト全体が止まらずに済みます。
この記事で使うAPI
pcallの使い方
local DataStoreService = game:GetService("DataStoreService")
local Players = game:GetService("Players")
local coinStore = DataStoreService:GetDataStore("PlayerCoins")
Players.PlayerAdded:Connect(function(player)
local success, coins = pcall(function()
return coinStore:GetAsync(tostring(player.UserId))
end)
if success then
print(player.Name .. " のコイン:" .. tostring(coins or 0))
else
warn("データを読み込めませんでした")
end
end)
Players.PlayerRemoving:Connect(function(player)
local success, err = pcall(function()
coinStore:SetAsync(tostring(player.UserId), 100)
end)
if not success then
warn("データを保存できませんでした:" .. tostring(err))
end
end)
pcall(関数) は、関数を実行して「成功したか」と「結果(または失敗の理由)」の2つを返します。失敗したときは warn で出力に知らせ、ゲームは止めずに続けます。
pcallを使う場面
- データの保存・読み込み(DataStoreService)
- 通信をともなう処理(購入・ほかのサーバーとのやりとりなど)