diff --git a/CHANGELOG.md b/CHANGELOG.md index a116899..14e9810 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,7 @@ # Changelog +- add `tryRun` method to PlayersData ([#8](https://github.com/seaofvoices/luau-disk/pull/8)) + ## 0.1.0 - Initial version diff --git a/README.md b/README.md index cba6935..791fe65 100644 --- a/README.md +++ b/README.md @@ -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(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(player: Player): Data` Retrieves the data associated with a specific player and raises an error if the data is not available. diff --git a/src/impl/PlayersData.lua b/src/impl/PlayersData.lua index d311774..ab4a334 100644 --- a/src/impl/PlayersData.lua +++ b/src/impl/PlayersData.lua @@ -1,5 +1,6 @@ export type PlayersData = { tryGet: (self: PlayersData, player: Player) -> Data?, + tryRun: (self: PlayersData, player: Player, fn: (Data) -> ()) -> boolean, expect: (self: PlayersData, player: Player) -> Data, restoreDefault: (self: PlayersData, player: Player) -> (), } @@ -12,6 +13,7 @@ type PlayersDataStatic = { new: (data: { [Player]: Data }, getDefault: () -> Data) -> PlayersData, tryGet: (self: PlayersData, player: Player) -> Data?, + tryRun: (self: PlayersData, player: Player, fn: (Data) -> ()) -> boolean, expect: (self: PlayersData, player: Player) -> Data, restoreDefault: (self: PlayersData, player: Player) -> (), } @@ -37,6 +39,18 @@ function PlayersData:tryGet(player: Player): Data? return self._data[player] end +function PlayersData:tryRun(player: Player, fn: (Data) -> ()): boolean + local self: PrivatePlayersData = self :: any + + local data = self._data[player] + if data ~= nil then + fn(data) + return true + end + + return false +end + function PlayersData:expect(player: Player): Data local self: PrivatePlayersData = self :: any