Skip to content

Commit

Permalink
Add PlayersData:forEach() function (#9)
Browse files Browse the repository at this point in the history
  • Loading branch information
jeparlefrancais authored Jun 21, 2024
1 parent dba0271 commit 13f6706
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# Changelog

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

## 0.1.0
Expand Down
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,14 @@ Retrieves the data associated with a specific player and raises an error if the
- **Returns:**
- `Data`: The player's data.

#### `forEach<Data>(fn: (player: Player, data: Data) -> ())`

Execute the given `fn` function for every player that has loaded data. The function **must not yield**.

- **Parameters:**

- `fn`: A function that will be called with every player with loaded data.

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

Updates the data associated with a specific player to match the default value.
Expand Down
10 changes: 10 additions & 0 deletions src/impl/PlayersData.lua
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ 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,
forEach: (self: PlayersData<Data>, fn: (player: Player, data: Data) -> ()) -> (),
restoreDefault: (self: PlayersData<Data>, player: Player) -> (),
}

Expand All @@ -15,6 +16,7 @@ type PlayersDataStatic = {
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,
forEach: <Data>(self: PlayersData<Data>, fn: (player: Player, data: Data) -> ()) -> (),
restoreDefault: <Data>(self: PlayersData<Data>, player: Player) -> (),
}
type PrivatePlayersData<Data> = PlayersData<Data> & Private<Data>
Expand Down Expand Up @@ -62,6 +64,14 @@ function PlayersData:expect<Data>(player: Player): Data
return data
end

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

for player, data in self._data do
fn(player, data)
end
end

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

Expand Down

0 comments on commit 13f6706

Please sign in to comment.