# Luau入門9：エラーで止まらないようにする（pcall）

> データの保存のように失敗することがある処理は、pcall で包むと、エラーが起きてもスクリプト全体が止まらずに済みます。

- URL：https://roblox.minecraft-okinawa.com/luau/pcall/
- 更新日：2026-11-13

## pcallの使い方

```lua
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）
- 通信をともなう処理（購入・ほかのサーバーとのやりとりなど）

## 出典

- [Luau 公式サイト](https://luau.org/)
- [Roblox Creator Documentation](https://create.roblox.com/docs)

執筆：鈴木孝昌（現役プロジェクトマネージャー／プログラミング講師）／運営：沖縄マイクラ部 プログラミングスクール「クロスウェーブ」（https://minecraft-okinawa.com/）