Skip to content

Commit

Permalink
Add PlayersData:tryRun() function (#8)
Browse files Browse the repository at this point in the history
  • Loading branch information
jeparlefrancais authored Jun 21, 2024
1 parent 07da89b commit dba0271
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 0 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# Changelog

- add `tryRun` method to PlayersData ([#8](https://github.com/seaofvoices/luau-disk/pull/8))

## 0.1.0

- Initial version
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,18 @@ Attempts to retrieve the data associated with a specific player.
- **Returns:**
- `Data`: The player's data if available, or `nil` if not found.

#### `tryRun<Data>(player: Player, fn: (Data) -> ()): boolean`

Execute the given `fn` function only if data is found for the given `Player`.

- **Parameters:**

- `player`: The player for whom data is to be retrieved.
- `fn`: A function that accepts the data associated with the player.

- **Returns:**
- `boolean`: If the `fn` function was called or not.

#### `expect<Data>(player: Player): Data`

Retrieves the data associated with a specific player and raises an error if the data is not available.
Expand Down
14 changes: 14 additions & 0 deletions src/impl/PlayersData.lua
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
export type PlayersData<Data> = {
tryGet: (self: PlayersData<Data>, player: Player) -> Data?,
tryRun: (self: PlayersData<Data>, player: Player, fn: (Data) -> ()) -> boolean,
expect: (self: PlayersData<Data>, player: Player) -> Data,
restoreDefault: (self: PlayersData<Data>, player: Player) -> (),
}
Expand All @@ -12,6 +13,7 @@ type PlayersDataStatic = {
new: <Data>(data: { [Player]: Data }, getDefault: () -> Data) -> PlayersData<Data>,

tryGet: <Data>(self: PlayersData<Data>, player: Player) -> Data?,
tryRun: <Data>(self: PlayersData<Data>, player: Player, fn: (Data) -> ()) -> boolean,
expect: <Data>(self: PlayersData<Data>, player: Player) -> Data,
restoreDefault: <Data>(self: PlayersData<Data>, player: Player) -> (),
}
Expand All @@ -37,6 +39,18 @@ function PlayersData:tryGet<Data>(player: Player): Data?
return self._data[player]
end

function PlayersData:tryRun<Data>(player: Player, fn: (Data) -> ()): boolean
local self: PrivatePlayersData<Data> = self :: any

local data = self._data[player]
if data ~= nil then
fn(data)
return true
end

return false
end

function PlayersData:expect<Data>(player: Player): Data
local self: PrivatePlayersData<Data> = self :: any

Expand Down

0 comments on commit dba0271

Please sign in to comment.