diff --git a/docs/api/calendar.md b/docs/api/calendar.md index 99c1756..27d9d7b 100644 --- a/docs/api/calendar.md +++ b/docs/api/calendar.md @@ -1,10 +1,9 @@ --- -description: "Calendar and date helpers." +title: "calendar" +description: "Calculate weekday alignments, leap years, and month lengths." --- -# `calendar` - -Calendar and date helpers. +Calculate weekday alignments, leap years, and month lengths. > [!WARNING] > @@ -14,49 +13,86 @@ Calendar and date helpers. ## Usage ```lua -cal = require "mods.calendar" +cal = mods.calendar print(cal.weekday(2026, 3, 26)) --> 4 ``` +## Fields + +### `days` ([`mods.List`]``) {#days} + +Weekday names indexed from `1` (Monday) to `7` (Sunday). + +```lua +print(cal.days[1]) --> Monday +print(cal.days[7]) --> Sunday +``` + +--- + +### `firstweekday` ([`mods.CalendarWeekday`]) {#firstweekday} + +The default first weekday field. + +```lua +print(cal.firstweekday) --> 1 +cal.firstweekday = cal.SUNDAY +print(cal.firstweekday) --> 7 +``` + +> [!NOTE] +> +> Reading or writing this property is equivalent to calling `getfirstweekday()` +> or `setfirstweekday()`. + +--- + +### `months` ([`mods.List`]``) {#months} + +Month names indexed from `1` to `12`. + +```lua +print(cal.months[1]) --> January +print(cal.months[12]) --> December +``` + ## Functions -| Function | Description | -| ------------------------------------------------------ | --------------------------------- | -| [`getfirstweekday()`](#fn-getfirstweekday) | Return the default first weekday. | -| [`setfirstweekday(firstweekday)`](#fn-setfirstweekday) | Set the default first weekday. | +| Function | Description | +| --------------------------------- | --------------------------------- | +| [`getfirstweekday()`] | Return the default first weekday. | +| [`setfirstweekday(firstweekday)`] | Set the default first weekday. | **Calendar Calculations**: -| Function | Description | -| ------------------------------------------- | ----------------------------------------------------------------------- | -| [`isleap(year)`](#fn-isleap) | Return `true` for leap years. | -| [`leapdays(y1, y2)`](#fn-leapdays) | Return the number of leap years from `y1` up to but not including `y2`. | -| [`monthrange(year, month)`](#fn-monthrange) | Return the first weekday and number of days for a month. | -| [`weekday(year, month, day)`](#fn-weekday) | Return weekday number where Monday is `1` and Sunday is `7`. | +| Function | Description | +| ----------------------------- | ----------------------------------------------------------------------- | +| [`isleap(year)`] | Return `true` for leap years. | +| [`leapdays(y1, y2)`] | Return the number of leap years from `y1` up to but not including `y2`. | +| [`monthrange(year, month)`] | Return the first weekday and number of days for a month. | +| [`weekday(year, month, day)`] | Return weekday number where Monday is `1` and Sunday is `7`. | **Formatting**: -| Function | Description | -| ----------------------------------------------------- | ------------------------------------------- | -| [`weekheader(width?, firstweekday?)`](#fn-weekheader) | Return the formatted weekday header string. | +| Function | Description | +| ------------------------------------- | ------------------------------------------- | +| [`weekheader(width?, firstweekday?)`] | Return the formatted weekday header string. | **Iterators**: -| Function | Description | -| -------------------------------------------------------- | ---------------------------------------------------------------------- | -| [`monthdays(year, month, firstweekday?)`](#fn-monthdays) | Iterate `(year, month, day, weekday)` tuples for a full calendar grid. | -| [`weekdays(firstweekday?)`](#fn-weekdays) | Iterate weekday numbers for one full week. | - - +| Function | Description | +| ----------------------------------------- | ---------------------------------------------------------------------- | +| [`monthdays(year, month, firstweekday?)`] | Iterate `(year, month, day, weekday)` tuples for a full calendar grid. | +| [`weekdays(firstweekday?)`] | Iterate weekday numbers for one full week. | -### `getfirstweekday()` +### `getfirstweekday()` {#getfirstweekday} Return the default first weekday. -**Return**: +**Returns**: -- `firstweekday` (`1|2|3|4|5|6|7`) +- `firstweekday` ([`mods.CalendarWeekday`]): Monday **Example**: @@ -69,15 +105,15 @@ print(cal.getfirstweekday()) --> 1 > > This returns the same value as `cal.firstweekday`. - +--- -### `setfirstweekday(firstweekday)` +### `setfirstweekday(firstweekday)` {#setfirstweekday} Set the default first weekday. **Parameters**: -- `firstweekday` (`1|2|3|4|5|6|7`) +- `firstweekday` ([`mods.CalendarWeekday`]): Monday **Example**: @@ -90,11 +126,11 @@ cal.setfirstweekday(cal.SUNDAY) > > This updates the same value as `cal.firstweekday = ...`. -### Calendar Calculations +--- - +### Calendar Calculations -#### `isleap(year)` +#### `isleap(year)` {#isleap} Return `true` for leap years. @@ -102,7 +138,7 @@ Return `true` for leap years. - `year` (`integer`) -**Return**: +**Returns**: - `isLeap` (`boolean`) @@ -113,9 +149,9 @@ local cal = mods.calendar print(cal.isleap(2024)) --> true ``` - +--- -#### `leapdays(y1, y2)` +#### `leapdays(y1, y2)` {#leapdays} Return the number of leap years from `y1` up to but not including `y2`. @@ -124,7 +160,7 @@ Return the number of leap years from `y1` up to but not including `y2`. - `y1` (`integer`) - `y2` (`integer`) -**Return**: +**Returns**: - `count` (`integer`) @@ -135,9 +171,9 @@ local cal = mods.calendar print(cal.leapdays(2000, 2025)) --> 7 ``` - +--- -#### `monthrange(year, month)` +#### `monthrange(year, month)` {#monthrange} Return the first weekday and number of days for a month. @@ -146,9 +182,9 @@ Return the first weekday and number of days for a month. - `year` (`integer`) - `month` (`integer`) -**Return**: +**Returns**: -- `weekday` (`1|2|3|4|5|6|7`) +- `weekday` ([`mods.CalendarWeekday`]): Monday - `ndays` (`integer`) **Example**: @@ -159,22 +195,21 @@ wday, ndays = cal.monthrange(2026, 2) print(wday, ndays) --> 7 28 ``` - +--- -#### `weekday(year, month, day)` +#### `weekday(year, month, day)` {#weekday} Return weekday number where Monday is `1` and Sunday is `7`. **Parameters**: - `year` (`integer`) -- `month` (`1|2|3|4|5|6|7|8|9|10|11|12`) -- `day` - (`1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|19|20|21|22|23|24|25|26|27|28|29|30|31`) +- `month` ([`mods.CalendarMonth`]): January +- `day` ([`mods.modsCalendarMonthday`]): 1st day of the month -**Return**: +**Returns**: -- `weekday` (`1|2|3|4|5|6|7`) +- `weekday` ([`mods.CalendarWeekday`]): Monday **Example**: @@ -183,20 +218,20 @@ local cal = mods.calendar print(cal.weekday(2026, 3, 26)) --> 4 ``` -### Formatting +--- - +### Formatting -#### `weekheader(width?, firstweekday?)` +#### `weekheader(width?, firstweekday?)` {#weekheader} Return the formatted weekday header string. **Parameters**: - `width?` (`integer`) -- `firstweekday?` (`1|2|3|4|5|6|7`) +- `firstweekday?` ([`mods.CalendarWeekday`]): Monday -**Return**: +**Returns**: - `header` (`string`) @@ -210,24 +245,24 @@ print(cal.weekheader(2, cal.SUNDAY)) --> "Su Mo Tu We Th Fr Sa" print(cal.weekheader(3, cal.SUNDAY)) --> "Sun Mon Tue Wed Thu Fri Sat" ``` -### Iterators +--- - +### Iterators -#### `monthdays(year, month, firstweekday?)` +#### `monthdays(year, month, firstweekday?)` {#monthdays} Iterate `(year, month, day, weekday)` tuples for a full calendar grid. **Parameters**: - `year` (`integer`) -- `month` (`1|2|3|4|5|6|7|8|9|10|11|12`) -- `firstweekday?` (`1|2|3|4|5|6|7`) +- `month` ([`mods.CalendarMonth`]): January +- `firstweekday?` ([`mods.CalendarWeekday`]): Monday -**Return**: +**Returns**: - `iter` - (`fun():year:integer,month:modsCalendarMonth,day:modsCalendarMonthday,weekday:modsCalendarWeekday`) + (`fun():year:integer,month:`[`mods.CalendarMonth`]`,day:`[`mods.modsCalendarMonthday`]`,weekday:`[`mods.CalendarWeekday`]) **Example**: @@ -261,19 +296,19 @@ print(lines:join("\n")) -- 23 24 25 26 27 28 ``` - +--- -#### `weekdays(firstweekday?)` +#### `weekdays(firstweekday?)` {#weekdays} Iterate weekday numbers for one full week. **Parameters**: -- `firstweekday?` (`1|2|3|4|5|6|7`) +- `firstweekday?` ([`mods.CalendarWeekday`]): Monday -**Return**: +**Returns**: -- `iter` (`fun():modsCalendarWeekday`) +- `iter` (`fun():`[`mods.CalendarWeekday`]) **Example**: @@ -286,43 +321,18 @@ end print(table.concat(weekdays, ", ")) --> "1, 2, 3, 4, 5, 6, 7" ``` -## Fields - - - -### `days` (`mods.List`) - -Weekday names indexed from `1` (Monday) to `7` (Sunday). - -```lua -print(cal.days[1]) --> Monday -print(cal.days[7]) --> Sunday -``` - - - -### `firstweekday` (`1|2|3|4|5|6|7`) - -The default first weekday field. - -```lua -print(cal.firstweekday) --> 1 -cal.firstweekday = cal.SUNDAY -print(cal.firstweekday) --> 7 -``` - -> [!NOTE] -> -> Reading or writing this property is equivalent to calling `getfirstweekday()` -> or `setfirstweekday()`. - - - -### `months` (`mods.List`) - -Month names indexed from `1` to `12`. - -```lua -print(cal.months[1]) --> January -print(cal.months[12]) --> December -``` + +[`getfirstweekday()`]: #getfirstweekday +[`isleap(year)`]: #isleap +[`leapdays(y1, y2)`]: #leapdays +[`mods.CalendarMonth`]: /mods/types#mods-calendarmonth +[`mods.CalendarWeekday`]: /mods/types#mods-calendarweekday +[`mods.List`]: /mods/api/list +[`mods.modsCalendarMonthday`]: /mods/types#mods-modscalendarmonthday +[`monthdays(year, month, firstweekday?)`]: #monthdays +[`monthrange(year, month)`]: #monthrange +[`setfirstweekday(firstweekday)`]: #setfirstweekday +[`weekday(year, month, day)`]: #weekday +[`weekdays(firstweekday?)`]: #weekdays +[`weekheader(width?, firstweekday?)`]: #weekheader + diff --git a/docs/api/date.md b/docs/api/date.md index c39f439..70afd1b 100644 --- a/docs/api/date.md +++ b/docs/api/date.md @@ -1,9 +1,8 @@ --- +title: "date" description: "Timezone-naive date helpers and immutable date values." --- -# `date` - Timezone-naive date helpers and immutable date values. ## Usage @@ -30,9 +29,8 @@ print(f) --> 2026-01-01 00:00:00 > [!NOTE] > -> - String inputs accept [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) -> forms, variants using a space instead of `T`, and custom formats via -> `Date(input, pattern)`: +> - String inputs accept [ISO 8601] forms, variants using a space instead of +> `T`, and custom formats via `Date(input, pattern)`: > > ```lua > Date("2026-03-30T14:45:06") @@ -41,7 +39,7 @@ print(f) --> 2026-01-01 00:00:00 > ``` > > - When `input` is a number, it is treated as Unix milliseconds. Use -> [`Date.unix(ts)`](#fn-unix) if you have a timestamp in seconds. +> [`Date.unix(ts)`] if you have a timestamp in seconds. > > ```lua > local a = Date(1745155206123) -- Milliseconds @@ -49,120 +47,218 @@ print(f) --> 2026-01-01 00:00:00 > print(a == b) --> true > ``` > -> - When calling `Date` without arguments, it uses -> [mstime](https://github.com/luamod/mstime) for millisecond precision if -> installed; otherwise it falls back to -> [`os.time`](https://www.lua.org/manual/5.1/manual.html#pdf-os.time). +> - When calling `Date` without arguments, it uses [mstime] for millisecond +> precision if installed; otherwise it falls back to [`os.time`]. + +## Fields + +| Field | Description | +| --------- | ------------------------------------------------------------ | +| [`day`] | Day-of-month component. | +| [`hour`] | Hour component. | +| [`min`] | Minute component. | +| [`month`] | Month component. | +| [`ms`] | Millisecond component. | +| [`sec`] | Second component. | +| [`wday`] | ISO weekday component where Monday is `1` and Sunday is `7`. | +| [`yday`] | Day-of-year component starting at `1`. | +| [`year`] | Year component. | + +### `day` (`modsCalendarMonthday`) {#day} + +Day-of-month component. + +```lua +print(Date("2026-03-30").day) --> 30 +``` + +--- + +### `hour` (`integer`) {#hour} + +Hour component. + +```lua +print(Date("2026-03-30T14:45:06").hour) --> 14 +``` + +--- + +### `min` (`integer`) {#min} + +Minute component. + +```lua +print(Date("2026-03-30T14:45:06").min) --> 45 +``` + +--- + +### `month` (`modsCalendarMonth`) {#month} + +Month component. + +```lua +print(Date("2026-03-30").month) --> 3 +``` + +--- + +### `ms` (`integer`) {#ms} + +Millisecond component. + +```lua +print(Date("2026-03-30T14:45:06.123").ms) --> 123 +``` + +--- + +### `sec` (`integer`) {#sec} + +Second component. + +```lua +print(Date("2026-03-30T14:45:06").sec) --> 6 +``` + +--- + +### `wday` (`modsCalendarWeekday`) {#wday} + +ISO weekday component where Monday is `1` and Sunday is `7`. + +```lua +print(Date("2026-03-30").wday) --> 1 +``` + +--- + +### `yday` (`integer`) {#yday} + +Day-of-year component starting at `1`. + +```lua +print(Date("2026-03-30").yday) --> 89 +``` + +--- + +### `year` (`integer`) {#year} + +Year component. + +```lua +print(Date("2026-03-30").year) --> 2026 +``` ## Functions -| Function | Description | -| --------------------------------- | ------------------------------------------------------------------------ | -| [`new(input, pattern?)`](#fn-new) | Create a Date from a string using an optional pattern. | -| [`new(input?)`](#fn-new) | Create a Date from a Unix timestamp (milliseconds) or a DateParts table. | +| Function | Description | +| ------------------------ | ------------------------------------------------------------------------ | +| [`new(input, pattern?)`] | Create a Date from a string using an optional pattern. | +| [`new(input?)`] | Create a Date from a Unix timestamp (milliseconds) or a DateParts table. | **Arithmetic**: -| Function | Description | -| ----------------------------------------- | ------------------------------------------------------------------- | -| [`add(amount, unit?)`](#fn-add) | Return a copy shifted by the given amount and unit. | -| [`diff(date, unit?)`](#fn-diff) | Return the signed difference to another Date in the requested unit. | -| [`subtract(amount, unit?)`](#fn-subtract) | Return a copy shifted backward by the given amount and unit. | +| Function | Description | +| --------------------------- | ------------------------------------------------------------------- | +| [`add(amount, unit?)`] | Return a copy shifted by the given amount and unit. | +| [`diff(date, unit?)`] | Return the signed difference to another Date in the requested unit. | +| [`subtract(amount, unit?)`] | Return a copy shifted backward by the given amount and unit. | **Boundaries**: -| Function | Description | -| ------------------------------ | --------------------------------------------- | -| [`endof(unit)`](#fn-endof) | Return the end boundary for the given unit. | -| [`startof(unit)`](#fn-startof) | Return the start boundary for the given unit. | +| Function | Description | +| ----------------- | --------------------------------------------- | +| [`endof(unit)`] | Return the end boundary for the given unit. | +| [`startof(unit)`] | Return the start boundary for the given unit. | **Calendar**: -| Function | Description | -| ----------------------------------------------------- | --------------------------------------------------------------------------- | -| [`day_of_year(day_of_year_number?)`](#fn-day-of-year) | Return or set the day of the year. | -| [`is_leap_year()`](#fn-is-leap-year) | Return `true` when the value's year is a leap year. | -| [`iso_week(iso_week_number?)`](#fn-iso-week) | Return or set the ISO week-of-year number. | -| [`iso_week_year()`](#fn-iso-week-year) | Return the ISO week-year for the current date. | -| [`iso_weekday(iso_weekday_number?)`](#fn-iso-weekday) | Return or set the ISO weekday number where Monday is `1` and Sunday is `7`. | -| [`iso_weeks_in_year()`](#fn-iso-weeks-in-year) | Return the number of ISO weeks in the current date's calendar year. | -| [`month_days()`](#fn-month-days) | Return the number of days in the value's month. | -| [`quarter(quarter_number?)`](#fn-quarter) | Return or set the quarter of the year. | -| [`week(week_number?)`](#fn-week) | Return or set the non-ISO week-of-year number. | -| [`week_year()`](#fn-week-year) | Return the non-ISO week-year for the current date. | -| [`weekday(weekday_number?)`](#fn-weekday) | Return or set the locale-relative weekday like Day.js `weekday()`. | -| [`weeks_in_year()`](#fn-weeks-in-year) | Return the number of weeks in the current locale week-year. | +| Function | Description | +| ------------------------------------ | --------------------------------------------------------------------------- | +| [`day_of_year(day_of_year_number?)`] | Return or set the day of the year. | +| [`is_leap_year()`] | Return `true` when the value's year is a leap year. | +| [`iso_week(iso_week_number?)`] | Return or set the ISO week-of-year number. | +| [`iso_week_year()`] | Return the ISO week-year for the current date. | +| [`iso_weekday(iso_weekday_number?)`] | Return or set the ISO weekday number where Monday is `1` and Sunday is `7`. | +| [`iso_weeks_in_year()`] | Return the number of ISO weeks in the current date's calendar year. | +| [`month_days()`] | Return the number of days in the value's month. | +| [`quarter(quarter_number?)`] | Return or set the quarter of the year. | +| [`week(week_number?)`] | Return or set the non-ISO week-of-year number. | +| [`week_year()`] | Return the non-ISO week-year for the current date. | +| [`weekday(weekday_number?)`] | Return or set the locale-relative weekday like Day.js `weekday()`. | +| [`weeks_in_year()`] | Return the number of weeks in the current locale week-year. | **Compare**: -| Function | Description | -| --------------------------- | ----------------------------------------------------------- | -| [`max(...)`](#fn-max) | Return the latest value from the given dates. | -| [`min(...)`](#fn-min) | Return the earliest value from the given dates. | -| [`minmax(...)`](#fn-minmax) | Return the earliest and latest values from the given dates. | +| Function | Description | +| --------------- | ----------------------------------------------------------- | +| [`max(...)`] | Return the latest value from the given dates. | +| [`min(...)`] | Return the earliest value from the given dates. | +| [`minmax(...)`] | Return the earliest and latest values from the given dates. | **Comparison**: -| Function | Description | -| ---------------------------------------------------------------- | ----------------------------------------------------------------- | -| [`is_after(date)`](#fn-is-after) | Return `true` when the value is later than `other`. | -| [`is_before(date)`](#fn-is-before) | Return `true` when the value is earlier than `other`. | -| [`is_between(start_date, end_date, inclusive?)`](#fn-is-between) | Return `true` when the value lies between two bounds. | -| [`is_same(date)`](#fn-is-same) | Return `true` when the value is equal to `other`. | -| [`is_same_or_after(date)`](#fn-is-same-or-after) | Return `true` when the value is later than or equal to `other`. | -| [`is_same_or_before(date)`](#fn-is-same-or-before) | Return `true` when the value is earlier than or equal to `other`. | -| [`is_today()`](#fn-is-today) | Return `true` when the value falls on the current local day. | -| [`is_tomorrow()`](#fn-is-tomorrow) | Return `true` when the value falls on the next local day. | -| [`is_yesterday()`](#fn-is-yesterday) | Return `true` when the value falls on the previous local day. | +| Function | Description | +| ------------------------------------------------ | ----------------------------------------------------------------- | +| [`is_after(date)`] | Return `true` when the value is later than `other`. | +| [`is_before(date)`] | Return `true` when the value is earlier than `other`. | +| [`is_between(start_date, end_date, inclusive?)`] | Return `true` when the value lies between two bounds. | +| [`is_same(date)`] | Return `true` when the value is equal to `other`. | +| [`is_same_or_after(date)`] | Return `true` when the value is later than or equal to `other`. | +| [`is_same_or_before(date)`] | Return `true` when the value is earlier than or equal to `other`. | +| [`is_today()`] | Return `true` when the value falls on the current local day. | +| [`is_tomorrow()`] | Return `true` when the value falls on the next local day. | +| [`is_yesterday()`] | Return `true` when the value falls on the previous local day. | **Duration**: -| Function | Description | -| --------------------------------------- | --------------------------------------------------------------------------- | -| [`is_duration(value)`](#fn-is-duration) | Return `true` when the value is a duration created by `date.duration(...)`. | +| Function | Description | +| ---------------------- | --------------------------------------------------------------------------- | +| [`is_duration(value)`] | Return `true` when the value is a duration created by `date.duration(...)`. | **Formatting**: -| Function | Description | -| ------------------------------- | ------------------------------------------------------------------------------------------------------- | -| [`format(pattern)`](#fn-format) | Format the Date with tokens like `YYYY`, `MMM`, `dddd`, `Do`, `Q`, `hh`, `k`, `X`, `x`, `A`, and `SSS`. | -| [`tostring()`](#fn-tostring) | Return the default string form `YYYY-MM-DD HH:mm:ss`. | +| Function | Description | +| ------------------- | ------------------------------------------------------------------------------------------------------- | +| [`format(pattern)`] | Format the Date with tokens like `YYYY`, `MMM`, `dddd`, `Do`, `Q`, `hh`, `k`, `X`, `x`, `A`, and `SSS`. | +| [`tostring()`] | Return the default string form `YYYY-MM-DD HH:mm:ss`. | **Relative Time**: -| Function | Description | -| ------------------------------------------- | -------------------------------------------------------------- | -| [`from(date, without_suffix?)`](#fn-from) | Return relative time from another Date to this one. | -| [`from_now(without_suffix?)`](#fn-from-now) | Return relative time from the current local time to this Date. | -| [`to(date, without_suffix?)`](#fn-to) | Return relative time from this Date to another one. | -| [`to_now(without_suffix?)`](#fn-to-now) | Return relative time from this Date to the current local time. | +| Function | Description | +| ------------------------------- | -------------------------------------------------------------- | +| [`from(date, without_suffix?)`] | Return relative time from another Date to this one. | +| [`from_now(without_suffix?)`] | Return relative time from the current local time to this Date. | +| [`to(date, without_suffix?)`] | Return relative time from this Date to another one. | +| [`to_now(without_suffix?)`] | Return relative time from this Date to the current local time. | **Unix**: -| Function | Description | -| ----------------------------- | ------------------------------------------------------------------- | -| [`unix(timestamp)`](#fn-unix) | Create a Date from a Unix timestamp in whole or fractional seconds. | +| Function | Description | +| ------------------- | ------------------------------------------------------------------- | +| [`unix(timestamp)`] | Create a Date from a Unix timestamp in whole or fractional seconds. | **Validation**: -| Function | Description | -| -------------------------------------------- | ----------------------------------------------------------- | -| [`is_valid(input?, pattern?)`](#fn-is-valid) | Return `true` when the input can be parsed as a valid Date. | +| Function | Description | +| ------------------------------ | ----------------------------------------------------------- | +| [`is_valid(input?, pattern?)`] | Return `true` when the input can be parsed as a valid Date. | **Metamethods**: -| Function | Description | -| ------------------------------ | ----------------------------------------------------------------------- | -| [`__add(a, b)`](#fn-add) | Return a copy shifted by integer milliseconds. | -| [`__eq(date)`](#fn-eq) | Return `true` when both Date values have identical components. | -| [`__le(date)`](#fn-le) | Return `true` when the left Date is earlier than or equal to the right. | -| [`__lt(date)`](#fn-lt) | Return `true` when the left Date is earlier than the right. | -| [`__sub(a, b)`](#fn-sub) | Return either a shifted copy or a millisecond delta. | -| [`__tostring()`](#fn-tostring) | Return the same result as `tostring()` when coerced to a string. | - - +| Function | Description | +| ---------------- | ----------------------------------------------------------------------- | +| [`__add(a, b)`] | Return a copy shifted by integer milliseconds. | +| [`__eq(date)`] | Return `true` when both Date values have identical components. | +| [`__le(date)`] | Return `true` when the left Date is earlier than or equal to the right. | +| [`__lt(date)`] | Return `true` when the left Date is earlier than the right. | +| [`__sub(a, b)`] | Return either a shifted copy or a millisecond delta. | +| [`__tostring()`] | Return the same result as `tostring()` when coerced to a string. | -### `new(input, pattern?)` +### `new(input, pattern?)` {#new-1} Create a Date from a string using an optional pattern. @@ -171,9 +267,9 @@ Create a Date from a string using an optional pattern. - `input` (`string`): The date string to parse. - `pattern?` (`string`): The format pattern. -**Return**: +**Returns**: -- **value** (`mods.Date`) +- **value** ([`mods.Date`]) **Example**: @@ -182,20 +278,20 @@ local d1 = Date("2026-03-30") local d2 = Date("12-25-1995", "MM-DD-YYYY") ``` - +--- -### `new(input?)` +### `new(input?)` {#new} Create a Date from a Unix timestamp (milliseconds) or a DateParts table. **Parameters**: -- `input?` (`number|mods.DateParts`): Unix timestamp (ms) or table of date +- `input?` (`number` | [`mods.DateParts`]): Unix timestamp (ms) or table of date components. -**Return**: +**Returns**: -- **value** (`mods.Date`) +- **value** ([`mods.Date`]) **Example**: @@ -204,25 +300,23 @@ local d1 = Date(1745155206123) local d2 = Date({ year = 2026, month = 3 }) ``` -### Arithmetic +--- - +### Arithmetic -#### `add(amount, unit?)` +#### `add(amount, unit?)` {#add} Return a copy shifted by the given amount and unit. **Parameters**: -- `amount` (`integer|mods.DateDurationParts`): Signed amount to add, or a +- `amount` (`integer` | [`mods.DateDurationParts`]): Signed amount to add, or a duration-style table. -- `unit?` - (`'ms'|'milliseconds'|'millisecond'|'s'|'secs'|'sec'|'seconds'|'second'|'m'|'mins'|'min'|'minutes'|'minute'|'h'|'hours'|'hour'|'d'|'days'|'day'|'w'|'weeks'|'week'|'M'|'months'|'month'|'q'|'quarters'|'quarter'|'y'|'years'|'year'`): - Unit for the addition. +- `unit?` ([`mods.DateUnit`]): Unit for the addition. -**Return**: +**Returns**: -- `shifted` (`mods.Date`): Shifted date value. +- `shifted` ([`mods.Date`]): Shifted date value. **Example**: @@ -236,20 +330,18 @@ print(d:add(250, "ms")) --> 2026-03-30 14:45:06.250 print(d:add({ month = 1, day = 2 })) --> 2026-05-02 14:45:06 ``` - +--- -#### `diff(date, unit?)` +#### `diff(date, unit?)` {#diff} Return the signed difference to another Date in the requested unit. **Parameters**: -- `date` (`mods.Date`): Date to compare against. -- `unit?` - (`'ms'|'milliseconds'|'millisecond'|'s'|'secs'|'sec'|'seconds'|'second'|'m'|'mins'|'min'|'minutes'|'minute'|'h'|'hours'|'hour'|'d'|'days'|'day'|'w'|'weeks'|'week'|'M'|'months'|'month'|'q'|'quarters'|'quarter'|'y'|'years'|'year'`): - Unit used for the difference. Defaults to `"ms"`. +- `date` ([`mods.Date`]): Date to compare against. +- `unit?` ([`mods.DateUnit`]): Unit used for the difference. Defaults to `"ms"`. -**Return**: +**Returns**: - `delta` (`integer`): Signed difference in whole units. @@ -262,23 +354,21 @@ print(a:diff(b, "month")) --> 1 print(a:diff(b, "day")) --> 30 ``` - +--- -#### `subtract(amount, unit?)` +#### `subtract(amount, unit?)` {#subtract} Return a copy shifted backward by the given amount and unit. **Parameters**: -- `amount` (`integer|mods.DateDurationParts`): Signed amount to subtract, or a - duration-style table. -- `unit?` - (`'ms'|'milliseconds'|'millisecond'|'s'|'secs'|'sec'|'seconds'|'second'|'m'|'mins'|'min'|'minutes'|'minute'|'h'|'hours'|'hour'|'d'|'days'|'day'|'w'|'weeks'|'week'|'M'|'months'|'month'|'q'|'quarters'|'quarter'|'y'|'years'|'year'`): - Unit for the subtraction. +- `amount` (`integer` | [`mods.DateDurationParts`]): Signed amount to subtract, + or a duration-style table. +- `unit?` ([`mods.DateUnit`]): Unit for the subtraction. -**Return**: +**Returns**: -- `shifted` (`mods.Date`): Shifted date value. +- `shifted` ([`mods.Date`]): Shifted date value. **Example**: @@ -291,21 +381,21 @@ print(d:subtract(250, "ms")) --> 2026-03-30 14:45:05.750 print(d:subtract({ month = 1, day = 1 })) --> 2026-02-27 14:45:06 ``` -### Boundaries +--- - +### Boundaries -#### `endof(unit)` +#### `endof(unit)` {#endof} Return the end boundary for the given unit. **Parameters**: -- `unit` (`mods.DateUnit|"isoWeek"`): Boundary unit. +- `unit` ([`mods.DateUnit`] | `"isoWeek"`): Boundary unit. -**Return**: +**Returns**: -- `bounded` (`mods.Date`): Date clamped to the end of the unit. +- `bounded` ([`mods.Date`]): Date clamped to the end of the unit. **Example**: @@ -318,19 +408,19 @@ print(d:endof("isoWeek")) --> 2026-04-05 23:59:59 `"isoWeek"` is also supported here as a boundary-only unit. - +--- -#### `startof(unit)` +#### `startof(unit)` {#startof} Return the start boundary for the given unit. **Parameters**: -- `unit` (`mods.DateUnit|"isoWeek"`): Boundary unit. +- `unit` ([`mods.DateUnit`] | `"isoWeek"`): Boundary unit. -**Return**: +**Returns**: -- `bounded` (`mods.Date`): Date clamped to the start of the unit. +- `bounded` ([`mods.Date`]): Date clamped to the start of the unit. **Example**: @@ -343,11 +433,11 @@ print(d:startof("isoWeek")) --> 2026-03-30 00:00:00 `"isoWeek"` is also supported here as a boundary-only unit. -### Calendar +--- - +### Calendar -#### `day_of_year(day_of_year_number?)` +#### `day_of_year(day_of_year_number?)` {#day-of-year} Return or set the day of the year. @@ -355,10 +445,10 @@ Return or set the day of the year. - `day_of_year_number?` (`integer`): Day-of-year to set. -**Return**: +**Returns**: -- `dayOrDate` (`integer|mods.Date`): Current day-of-year number, or a shifted - Date when `day_of_year_number` is provided. +- `dayOrDate` (`integer` | [`mods.Date`]): Current day-of-year number, or a + shifted Date when `day_of_year_number` is provided. **Example**: @@ -368,13 +458,13 @@ print(d:day_of_year()) --> 89 print(d:day_of_year(1)) --> 2026-01-01 00:00:00 ``` - +--- -#### `is_leap_year()` +#### `is_leap_year()` {#is-leap-year} Return `true` when the value's year is a leap year. -**Return**: +**Returns**: - `isLeapYear` (`boolean`): Whether the year is a leap year. @@ -384,9 +474,9 @@ Return `true` when the value's year is a leap year. print(Date("2024-02-29"):is_leap_year()) --> true ``` - +--- -#### `iso_week(iso_week_number?)` +#### `iso_week(iso_week_number?)` {#iso-week} Return or set the ISO week-of-year number. @@ -394,10 +484,10 @@ Return or set the ISO week-of-year number. - `iso_week_number?` (`integer`): ISO week number to set. -**Return**: +**Returns**: -- `isoWeekOrDate` (`integer|mods.Date`): Current ISO week number, or a shifted - Date when `iso_week_number` is provided. +- `isoWeekOrDate` (`integer` | [`mods.Date`]): Current ISO week number, or a + shifted Date when `iso_week_number` is provided. **Example**: @@ -407,13 +497,13 @@ print(d:iso_week()) --> 14 print(d:iso_week(15)) --> 2026-04-06 00:00:00 ``` - +--- -#### `iso_week_year()` +#### `iso_week_year()` {#iso-week-year} Return the ISO week-year for the current date. -**Return**: +**Returns**: - `isoWeekYear` (`integer`): ISO week-year. @@ -423,9 +513,9 @@ Return the ISO week-year for the current date. print(Date("2021-01-01"):iso_week_year()) --> 2020 ``` - +--- -#### `iso_weekday(iso_weekday_number?)` +#### `iso_weekday(iso_weekday_number?)` {#iso-weekday} Return or set the ISO weekday number where Monday is `1` and Sunday is `7`. @@ -433,10 +523,10 @@ Return or set the ISO weekday number where Monday is `1` and Sunday is `7`. - `iso_weekday_number?` (`integer`): ISO weekday to set. -**Return**: +**Returns**: -- `isoWeekdayOrDate` (`modsCalendarWeekday|mods.Date`): Current ISO weekday - number, or a shifted Date when `iso_weekday_number` is provided. +- `isoWeekdayOrDate` (`modsCalendarWeekday` | [`mods.Date`]): Current ISO + weekday number, or a shifted Date when `iso_weekday_number` is provided. **Example**: @@ -446,13 +536,13 @@ print(d:iso_weekday()) --> 1 print(d:iso_weekday(7)) --> 2026-04-05 00:00:00 ``` - +--- -#### `iso_weeks_in_year()` +#### `iso_weeks_in_year()` {#iso-weeks-in-year} Return the number of ISO weeks in the current date's calendar year. -**Return**: +**Returns**: - `isoWeeksInYear` (`integer`): Number of ISO weeks in the current date's calendar year. @@ -465,13 +555,13 @@ print(Date("2016-01-01"):iso_weeks_in_year()) --> 52 print(Date("2016-06-01"):iso_weeks_in_year()) --> 52 ``` - +--- -#### `month_days()` +#### `month_days()` {#month-days} Return the number of days in the value's month. -**Return**: +**Returns**: - `ndays` (`modsCalendarMonthday`): Number of days in the current month. @@ -481,9 +571,9 @@ Return the number of days in the value's month. print(Date("2024-02-01"):month_days()) --> 29 ``` - +--- -#### `quarter(quarter_number?)` +#### `quarter(quarter_number?)` {#quarter} Return or set the quarter of the year. @@ -491,10 +581,10 @@ Return or set the quarter of the year. - `quarter_number?` (`integer`): Quarter to set. -**Return**: +**Returns**: -- `quarterOrDate` (`integer|mods.Date`): Current quarter number, or a shifted - Date when `quarter_number` is provided. +- `quarterOrDate` (`integer` | [`mods.Date`]): Current quarter number, or a + shifted Date when `quarter_number` is provided. **Example**: @@ -504,9 +594,9 @@ print(d:quarter()) --> 1 print(d:quarter(2)) --> 2026-06-30 00:00:00 ``` - +--- -#### `week(week_number?)` +#### `week(week_number?)` {#week} Return or set the non-ISO week-of-year number. @@ -514,10 +604,10 @@ Return or set the non-ISO week-of-year number. - `week_number?` (`integer`): Week number to set. -**Return**: +**Returns**: -- `weekOrDate` (`integer|mods.Date`): Current week-of-year number, or a shifted - Date when `week_number` is provided. +- `weekOrDate` (`integer` | [`mods.Date`]): Current week-of-year number, or a + shifted Date when `week_number` is provided. **Example**: @@ -527,13 +617,13 @@ print(d:week()) --> 14 print(d:week(15)) --> 2026-04-06 00:00:00 ``` - +--- -#### `week_year()` +#### `week_year()` {#week-year} Return the non-ISO week-year for the current date. -**Return**: +**Returns**: - `weekYear` (`integer`): Week-year. @@ -543,9 +633,9 @@ Return the non-ISO week-year for the current date. print(Date("2021-01-01"):week_year()) --> 2021 ``` - +--- -#### `weekday(weekday_number?)` +#### `weekday(weekday_number?)` {#weekday} Return or set the locale-relative weekday like Day.js `weekday()`. @@ -553,10 +643,10 @@ Return or set the locale-relative weekday like Day.js `weekday()`. - `weekday_number?` (`integer`): Locale-relative weekday to set. -**Return**: +**Returns**: -- `weekdayOrDate` (`integer|mods.Date`): Current locale-relative weekday number, - or a shifted Date when `weekday_number` is provided. +- `weekdayOrDate` (`integer` | [`mods.Date`]): Current locale-relative weekday + number, or a shifted Date when `weekday_number` is provided. **Example**: @@ -568,17 +658,17 @@ print(d:weekday(-7)) --> 2026-03-23 00:00:00 ``` The getter returns a number in the range `0..6`, relative to the current -`mods.calendar.firstweekday`. Passing an integer returns a shifted copy in the +[`mods.calendar.firstweekday`]. Passing an integer returns a shifted copy in the same locale-relative week space, with negative and overflow values moving into previous or next weeks. - +--- -#### `weeks_in_year()` +#### `weeks_in_year()` {#weeks-in-year} Return the number of weeks in the current locale week-year. -**Return**: +**Returns**: - `weeksInYear` (`integer`): Number of weeks. @@ -588,22 +678,22 @@ Return the number of weeks in the current locale week-year. print(Date("2026-03-30"):weeks_in_year()) --> 52 ``` -### Compare +--- - +### Compare -#### `max(...)` +#### `max(...)` {#max} Return the latest value from the given dates. **Parameters**: -- `...` (`mods.Date|mods.Date[]`): Date values to compare. Each argument may be - a date or a list of dates. +- `...` ([`mods.Date`] | [`mods.Date`]`[]`): Date values to compare. Each + argument may be a date or a list of dates. -**Return**: +**Returns**: -- `date` (`mods.Date`): Latest date value. +- `date` ([`mods.Date`]): Latest date value. **Example**: @@ -614,20 +704,20 @@ print(Date.max(a, b)) --> 2026-03-31 00:00:00 print(Date.max({ a, b })) --> 2026-03-31 00:00:00 ``` - +--- -#### `min(...)` +#### `min(...)` {#min-1} Return the earliest value from the given dates. **Parameters**: -- `...` (`mods.Date|mods.Date[]`): Date values to compare. Each argument may be - a date or a list of dates. +- `...` ([`mods.Date`] | [`mods.Date`]`[]`): Date values to compare. Each + argument may be a date or a list of dates. -**Return**: +**Returns**: -- `date` (`mods.Date`): Earliest date value. +- `date` ([`mods.Date`]): Earliest date value. **Example**: @@ -638,21 +728,21 @@ print(Date.min(a, b)) --> 2026-03-28 00:00:00 print(Date.min({ a, b })) --> 2026-03-28 00:00:00 ``` - +--- -#### `minmax(...)` +#### `minmax(...)` {#minmax} Return the earliest and latest values from the given dates. **Parameters**: -- `...` (`mods.Date|mods.Date[]`): Date values to compare. Each argument may be - a date or a list of dates. +- `...` ([`mods.Date`] | [`mods.Date`]`[]`): Date values to compare. Each + argument may be a date or a list of dates. -**Return**: +**Returns**: -- `minDate` (`mods.Date`): Earliest date value. -- `maxDate` (`mods.Date`): Latest date value. +- `minDate` ([`mods.Date`]): Earliest date value. +- `maxDate` ([`mods.Date`]): Latest date value. **Example**: @@ -665,19 +755,19 @@ print(min_date) --> 2026-03-28 00:00:00 print(max_date) --> 2026-03-31 00:00:00 ``` -### Comparison +--- - +### Comparison -#### `is_after(date)` +#### `is_after(date)` {#is-after} Return `true` when the value is later than `other`. **Parameters**: -- `date` (`mods.Date`): Date to compare against. +- `date` ([`mods.Date`]): Date to compare against. -**Return**: +**Returns**: - `isAfter` (`boolean`): Whether the value is later than `date`. @@ -689,17 +779,17 @@ local b = Date("2026-03-30T12:00:00") print(a:is_after(b)) --> true ``` - +--- -#### `is_before(date)` +#### `is_before(date)` {#is-before} Return `true` when the value is earlier than `other`. **Parameters**: -- `date` (`mods.Date`): Date to compare against. +- `date` ([`mods.Date`]): Date to compare against. -**Return**: +**Returns**: - `isBefore` (`boolean`): Whether the value is earlier than `date`. @@ -711,9 +801,9 @@ local b = Date("2026-03-31T12:00:00") print(a:is_before(b)) --> true ``` - +--- -#### `is_between(start_date, end_date, inclusive?)` +#### `is_between(start_date, end_date, inclusive?)` {#is-between} Return `true` when the value lies between two bounds. @@ -722,12 +812,12 @@ pass `true` as the third argument to include the endpoints. **Parameters**: -- `start_date` (`mods.Date`): One bound. -- `end_date` (`mods.Date`): The other bound. +- `start_date` ([`mods.Date`]): One bound. +- `end_date` ([`mods.Date`]): The other bound. - `inclusive?` (`boolean`): Whether to include the endpoints. Defaults to `false`. -**Return**: +**Returns**: - `isBetween` (`boolean`): Whether the value lies between the two bounds. @@ -742,17 +832,17 @@ print(a:is_between(a, b)) --> false print(a:is_between(a, b, true)) --> true ``` - +--- -#### `is_same(date)` +#### `is_same(date)` {#is-same} Return `true` when the value is equal to `other`. **Parameters**: -- `date` (`mods.Date`): Date to compare against. +- `date` ([`mods.Date`]): Date to compare against. -**Return**: +**Returns**: - `isSame` (`boolean`): Whether the value is equal to `date`. @@ -764,17 +854,17 @@ local b = Date("2026-03-30T12:00:00") print(a:is_same(b)) --> true ``` - +--- -#### `is_same_or_after(date)` +#### `is_same_or_after(date)` {#is-same-or-after} Return `true` when the value is later than or equal to `other`. **Parameters**: -- `date` (`mods.Date`): Date to compare against. +- `date` ([`mods.Date`]): Date to compare against. -**Return**: +**Returns**: - `isSameOrAfter` (`boolean`): Whether the value is later than or equal to `date`. @@ -789,17 +879,17 @@ print(a:is_same_or_after(b)) --> true print(a:is_same_or_after(c)) --> true ``` - +--- -#### `is_same_or_before(date)` +#### `is_same_or_before(date)` {#is-same-or-before} Return `true` when the value is earlier than or equal to `other`. **Parameters**: -- `date` (`mods.Date`): Date to compare against. +- `date` ([`mods.Date`]): Date to compare against. -**Return**: +**Returns**: - `isSameOrBefore` (`boolean`): Whether the value is earlier than or equal to `date`. @@ -814,13 +904,13 @@ print(a:is_same_or_before(b)) --> true print(a:is_same_or_before(c)) --> true ``` - +--- -#### `is_today()` +#### `is_today()` {#is-today} Return `true` when the value falls on the current local day. -**Return**: +**Returns**: - `isToday` (`boolean`): Whether the value is on today in local time. @@ -830,13 +920,13 @@ Return `true` when the value falls on the current local day. print(Date():is_today()) --> true ``` - +--- -#### `is_tomorrow()` +#### `is_tomorrow()` {#is-tomorrow} Return `true` when the value falls on the next local day. -**Return**: +**Returns**: - `isTomorrow` (`boolean`): Whether the value is on tomorrow in local time. @@ -846,13 +936,13 @@ Return `true` when the value falls on the next local day. print(Date():add(1, "day"):is_tomorrow()) --> true ``` - +--- -#### `is_yesterday()` +#### `is_yesterday()` {#is-yesterday} Return `true` when the value falls on the previous local day. -**Return**: +**Returns**: - `isYesterday` (`boolean`): Whether the value is on yesterday in local time. @@ -862,11 +952,11 @@ Return `true` when the value falls on the previous local day. print(Date():subtract(1, "day"):is_yesterday()) --> true ``` -### Duration +--- - +### Duration -#### `is_duration(value)` +#### `is_duration(value)` {#is-duration} Return `true` when the value is a duration created by `date.duration(...)`. @@ -874,9 +964,9 @@ Return `true` when the value is a duration created by `date.duration(...)`. - `value` (`any`): Value to test. -**Return**: +**Returns**: -- `isDuration` (`boolean`): Whether the value is a `mods.Duration`. +- `isDuration` (`boolean`): Whether the value is a [`mods.Duration`]. **Example**: @@ -886,11 +976,11 @@ print(date.is_duration(shift)) --> true print(date.is_duration({ day = 2 })) --> false ``` -### Formatting +--- - +### Formatting -#### `format(pattern)` +#### `format(pattern)` {#format} Format the Date with tokens like `YYYY`, `MMM`, `dddd`, `Do`, `Q`, `hh`, `k`, `X`, `x`, `A`, and `SSS`. @@ -899,7 +989,7 @@ Format the Date with tokens like `YYYY`, `MMM`, `dddd`, `Do`, `Q`, `hh`, `k`, - `pattern` (`string`): Format pattern using supported tokens. -**Return**: +**Returns**: - `formatted` (`string`): Formatted datetime string. @@ -988,13 +1078,13 @@ English preset aliases: | `lll` | `MMM D, YYYY h:mm A` | | `llll` | `ddd, MMM D, YYYY h:mm A` | - +--- -#### `tostring()` +#### `tostring()` {#tostring} Return the default string form `YYYY-MM-DD HH:mm:ss`. -**Return**: +**Returns**: - `s` (`string`): Default datetime string. @@ -1004,11 +1094,11 @@ Return the default string form `YYYY-MM-DD HH:mm:ss`. print(Date("2026-03-30T14:45:06.123")) --> 2026-03-30 14:45:06.123 ``` -### Relative Time +--- - +### Relative Time -#### `from(date, without_suffix?)` +#### `from(date, without_suffix?)` {#from} Return relative time from another Date to this one. @@ -1017,10 +1107,10 @@ By default the result includes a suffix like `ago` or a prefix like `in`. Pass **Parameters**: -- `date` (`mods.Date`): Reference date. +- `date` ([`mods.Date`]): Reference date. - `without_suffix?` (`boolean`): Whether to omit `ago` / `in`. -**Return**: +**Returns**: - `relative` (`string`): Relative time string. @@ -1033,9 +1123,9 @@ print(a:from(b)) --> in 2 hours print(a:from(b, true)) --> 2 hours ``` - +--- -#### `from_now(without_suffix?)` +#### `from_now(without_suffix?)` {#from-now} Return relative time from the current local time to this Date. @@ -1043,7 +1133,7 @@ Return relative time from the current local time to this Date. - `without_suffix?` (`boolean`): Whether to omit `ago` / `in`. -**Return**: +**Returns**: - `relative` (`string`): Relative time string. @@ -1054,9 +1144,9 @@ local d = date():add(1, "day") print(d:from_now()) --> in a day ``` - +--- -#### `to(date, without_suffix?)` +#### `to(date, without_suffix?)` {#to} Return relative time from this Date to another one. @@ -1065,10 +1155,10 @@ By default the result includes a suffix like `ago` or a prefix like `in`. Pass **Parameters**: -- `date` (`mods.Date`): Reference date. +- `date` ([`mods.Date`]): Reference date. - `without_suffix?` (`boolean`): Whether to omit `ago` / `in`. -**Return**: +**Returns**: - `relative` (`string`): Relative time string. @@ -1081,9 +1171,9 @@ print(a:to(b)) --> in 2 hours print(a:to(b, true)) --> 2 hours ``` - +--- -#### `to_now(without_suffix?)` +#### `to_now(without_suffix?)` {#to-now} Return relative time from this Date to the current local time. @@ -1091,7 +1181,7 @@ Return relative time from this Date to the current local time. - `without_suffix?` (`boolean`): Whether to omit `ago` / `in`. -**Return**: +**Returns**: - `relative` (`string`): Relative time string. @@ -1102,11 +1192,11 @@ local d = date():subtract(1, "day") print(d:to_now()) --> in a day ``` -### Unix +--- - +### Unix -#### `unix(timestamp)` +#### `unix(timestamp)` {#unix} Create a Date from a Unix timestamp in whole or fractional seconds. @@ -1114,9 +1204,9 @@ Create a Date from a Unix timestamp in whole or fractional seconds. - `timestamp` (`number`): Unix timestamp in whole or fractional seconds. -**Return**: +**Returns**: -- `date` (`mods.Date`): Date value for the given Unix timestamp. +- `date` ([`mods.Date`]): Date value for the given Unix timestamp. **Example**: @@ -1125,11 +1215,11 @@ print(Date.unix(1318781876)) --> 2011-10-16 18:17:56 print(Date.unix(1318781876.721).year) --> 2011 ``` -### Validation +--- - +### Validation -#### `is_valid(input?, pattern?)` +#### `is_valid(input?, pattern?)` {#is-valid} Return `true` when the input can be parsed as a valid Date. @@ -1138,11 +1228,11 @@ Unlike `Date(...)`, this helper never raises for invalid input; it just returns **Parameters**: -- `input?` (`string|number|mods.DateParts`): Value accepted by `Date(...)`. - `nil` returns `false`. +- `input?` (`string` | `number` | [`mods.DateParts`]): Value accepted by + `Date(...)`. `nil` returns `false`. - `pattern?` (`string`): Custom parse pattern used for string input. -**Return**: +**Returns**: - `isValid` (`boolean`): Whether the input is parseable as a valid Date. @@ -1155,11 +1245,11 @@ print(Date.is_valid("2026-02-29")) --> false print(Date.is_valid("12-25-1995", "MM-DD-YYYY")) --> true ``` -### Metamethods +--- - +### Metamethods -#### `__add(a, b)` +#### `__add(a, b)` {#add-1} Return a copy shifted by integer milliseconds. @@ -1167,12 +1257,12 @@ This works as either `date + ms` or `ms + date`. **Parameters**: -- `a` (`integer|mods.Date`): Milliseconds to add, or another Date. -- `b` (`integer|mods.Date`): Milliseconds to add, or another Date. +- `a` (`integer` | [`mods.Date`]): Milliseconds to add, or another Date. +- `b` (`integer` | [`mods.Date`]): Milliseconds to add, or another Date. -**Return**: +**Returns**: -- `sum` (`mods.Date`): Sum of the two dates. +- `sum` ([`mods.Date`]): Sum of the two dates. **Example**: @@ -1182,17 +1272,17 @@ print((d + 250)) --> 2026-03-30 14:45:06.250 print((250 + d)) --> 2026-03-30 14:45:06.250 ``` - +--- -#### `__eq(date)` +#### `__eq(date)` {#eq} Return `true` when both Date values have identical components. **Parameters**: -- `date` (`mods.Date`): Date to compare against. +- `date` ([`mods.Date`]): Date to compare against. -**Return**: +**Returns**: - `isEqual` (`boolean`): `true` if both dates are equal, `false` otherwise. @@ -1202,17 +1292,17 @@ Return `true` when both Date values have identical components. print(Date("2026-03-30") == Date("2026-03-30")) --> true ``` - +--- -#### `__le(date)` +#### `__le(date)` {#le} Return `true` when the left Date is earlier than or equal to the right. **Parameters**: -- `date` (`mods.Date`): Date to compare against. +- `date` ([`mods.Date`]): Date to compare against. -**Return**: +**Returns**: - `isEarlierOrEqual` (`boolean`): `true` if the left date is earlier or equal, `false` otherwise. @@ -1223,17 +1313,17 @@ Return `true` when the left Date is earlier than or equal to the right. print(Date("2026-03-30") <= Date("2026-03-30")) --> true ``` - +--- -#### `__lt(date)` +#### `__lt(date)` {#lt} Return `true` when the left Date is earlier than the right. **Parameters**: -- `date` (`mods.Date`): Date to compare against. +- `date` ([`mods.Date`]): Date to compare against. -**Return**: +**Returns**: - `isEarlier` (`boolean`): `true` if the left date is earlier, `false` otherwise. @@ -1244,9 +1334,9 @@ Return `true` when the left Date is earlier than the right. print(Date("2026-03-30") < Date("2026-03-31")) --> true ``` - +--- -#### `__sub(a, b)` +#### `__sub(a, b)` {#sub} Return either a shifted copy or a millisecond delta. @@ -1255,12 +1345,12 @@ subtracting another Date, it returns the signed millisecond difference. **Parameters**: -- `a` (`integer|mods.Date`): Milliseconds to subtract, or another Date. -- `b` (`integer|mods.Date`): Milliseconds to subtract, or another Date. +- `a` (`integer` | [`mods.Date`]): Milliseconds to subtract, or another Date. +- `b` (`integer` | [`mods.Date`]): Milliseconds to subtract, or another Date. -**Return**: +**Returns**: -- `delta` (`mods.Date|integer`): Difference between dates. +- `delta` ([`mods.Date`] | `integer`): Difference between dates. **Example**: @@ -1271,13 +1361,13 @@ print((a - 250)) --> 2026-03-30 14:45:06 print(a - b) --> 250 ``` - +--- -#### `__tostring()` +#### `__tostring()` {#tostring-1} Return the same result as `tostring()` when coerced to a string. -**Return**: +**Returns**: - `string` (`string`): representation of the date. @@ -1287,106 +1377,70 @@ Return the same result as `tostring()` when coerced to a string. print(Date("2026-03-30T14:45:06")) --> 2026-03-30 14:45:06 ``` -## Fields - -| Field | Description | -| ----------------- | ------------------------------------------------------------ | -| [`day`](#day) | Day-of-month component. | -| [`hour`](#hour) | Hour component. | -| [`min`](#min) | Minute component. | -| [`month`](#month) | Month component. | -| [`ms`](#ms) | Millisecond component. | -| [`sec`](#sec) | Second component. | -| [`wday`](#wday) | ISO weekday component where Monday is `1` and Sunday is `7`. | -| [`yday`](#yday) | Day-of-year component starting at `1`. | -| [`year`](#year) | Year component. | - - - -### `day` (`modsCalendarMonthday`) - -Day-of-month component. - -```lua -print(Date("2026-03-30").day) --> 30 -``` - - - -### `hour` (`integer`) - -Hour component. - -```lua -print(Date("2026-03-30T14:45:06").hour) --> 14 -``` - - - -### `min` (`integer`) - -Minute component. - -```lua -print(Date("2026-03-30T14:45:06").min) --> 45 -``` - - - -### `month` (`modsCalendarMonth`) - -Month component. - -```lua -print(Date("2026-03-30").month) --> 3 -``` - - - -### `ms` (`integer`) - -Millisecond component. - -```lua -print(Date("2026-03-30T14:45:06.123").ms) --> 123 -``` - - - -### `sec` (`integer`) - -Second component. - -```lua -print(Date("2026-03-30T14:45:06").sec) --> 6 -``` - - - -### `wday` (`modsCalendarWeekday`) - -ISO weekday component where Monday is `1` and Sunday is `7`. - -```lua -print(Date("2026-03-30").wday) --> 1 -``` - - - -### `yday` (`integer`) - -Day-of-year component starting at `1`. - -```lua -print(Date("2026-03-30").yday) --> 89 -``` - - - -### `year` (`integer`) - -Year component. - -```lua -print(Date("2026-03-30").year) --> 2026 -``` + +[ISO 8601]: https://en.wikipedia.org/wiki/ISO_8601 +[`Date.unix(ts)`]: #fn-unix +[`__add(a, b)`]: #add-1 +[`__eq(date)`]: #eq +[`__le(date)`]: #le +[`__lt(date)`]: #lt +[`__sub(a, b)`]: #sub +[`__tostring()`]: #tostring-1 +[`add(amount, unit?)`]: #add +[`day_of_year(day_of_year_number?)`]: #day-of-year +[`day`]: #day +[`diff(date, unit?)`]: #diff +[`endof(unit)`]: #endof +[`format(pattern)`]: #format +[`from(date, without_suffix?)`]: #from +[`from_now(without_suffix?)`]: #from-now +[`hour`]: #hour +[`is_after(date)`]: #is-after +[`is_before(date)`]: #is-before +[`is_between(start_date, end_date, inclusive?)`]: #is-between +[`is_duration(value)`]: #is-duration +[`is_leap_year()`]: #is-leap-year +[`is_same(date)`]: #is-same +[`is_same_or_after(date)`]: #is-same-or-after +[`is_same_or_before(date)`]: #is-same-or-before +[`is_today()`]: #is-today +[`is_tomorrow()`]: #is-tomorrow +[`is_valid(input?, pattern?)`]: #is-valid +[`is_yesterday()`]: #is-yesterday +[`iso_week(iso_week_number?)`]: #iso-week +[`iso_week_year()`]: #iso-week-year +[`iso_weekday(iso_weekday_number?)`]: #iso-weekday +[`iso_weeks_in_year()`]: #iso-weeks-in-year +[`max(...)`]: #max +[`min(...)`]: #min-1 +[`min`]: #min +[`minmax(...)`]: #minmax +[`mods.DateDurationParts`]: /mods/types#mods-datedurationparts +[`mods.DateParts`]: /mods/types#mods-dateparts +[`mods.DateUnit`]: /mods/types#mods-dateunit +[`mods.Date`]: /mods/api/date +[`mods.Duration`]: /mods/api/duration +[`mods.calendar.firstweekday`]: /mods/api/calendar#firstweekday +[`month_days()`]: #month-days +[`month`]: #month +[`ms`]: #ms +[`new(input, pattern?)`]: #new-1 +[`new(input?)`]: #new +[`os.time`]: https://www.lua.org/manual/5.1/manual.html#pdf-os.time +[`quarter(quarter_number?)`]: #quarter +[`sec`]: #sec +[`startof(unit)`]: #startof +[`subtract(amount, unit?)`]: #subtract +[`to(date, without_suffix?)`]: #to +[`to_now(without_suffix?)`]: #to-now +[`tostring()`]: #tostring +[`unix(timestamp)`]: #unix +[`wday`]: #wday +[`week(week_number?)`]: #week +[`week_year()`]: #week-year +[`weekday(weekday_number?)`]: #weekday +[`weeks_in_year()`]: #weeks-in-year +[`yday`]: #yday +[`year`]: #year +[mstime]: https://github.com/luamod/mstime + diff --git a/docs/api/duration.md b/docs/api/duration.md index 3386860..77fbdf3 100644 --- a/docs/api/duration.md +++ b/docs/api/duration.md @@ -1,10 +1,9 @@ --- +title: "duration" description: "Reusable immutable duration values for date arithmetic and formatting." --- -# `duration` - Reusable immutable duration values for date arithmetic and formatting. ## Usage @@ -18,121 +17,119 @@ print(shift:format("D [days] HH:mm")) --> 2 days 03:00 ## Functions -| Function | Description | -| --------------------------------------- | -------------------------------------------------------------------------------------------------------- | -| [`is_duration(value)`](#fn-is-duration) | Return `true` when the value is a duration created by `mods.duration(...)` or `mods.date.duration(...)`. | -| [`new(input, unit?)`](#fn-new) | Create a duration from a numeric amount and unit. | -| [`new(input?)`](#fn-new) | Create a duration from numeric parts, an ISO 8601 string, or another duration. | +| Function | Description | +| ---------------------- | ------------------------------------------------------------------------------------------------------------ | +| [`new(input, unit?)`] | Create a duration from a numeric amount and unit. | +| [`new(input?)`] | Create a duration from numeric parts, an ISO 8601 string, or another duration. | +| [`is_duration(value)`] | Return `true` when the value is a duration created by [`mods.duration(...)`] or [`mods.date.duration(...)`]. | **Duration**: -| Function | Description | -| ------------------------------------------------------------- | ------------------------------------------------------------------------- | -| [`add(value, unit?)`](#fn-add) | Return a new duration with another duration or unit amount added. | -| [`as(unit)`](#fn-as) | Return the duration expressed in the requested unit. | -| [`clone()`](#fn-clone) | Return a shallow copy of the duration value. | -| [`compare(other)`](#fn-compare) | Compare this duration to another duration-like value. | -| [`equals(other)`](#fn-equals) | Return `true` when both duration values have identical components. | -| [`format(pattern)`](#fn-format) | Format the duration using duration tokens like `Y`, `MM`, `DD`, and `HH`. | -| [`humanize(with_suffix_or_options?, options?)`](#fn-humanize) | Return a human-readable relative-style phrase for the duration. | -| [`normalize()`](#fn-normalize) | Return a compacted duration using the module's canonical carry rules. | -| [`subtract(value, unit?)`](#fn-subtract) | Return a new duration with another duration or unit amount subtracted. | -| [`to_iso()`](#fn-to-iso) | Return an ISO 8601 duration string. | -| [`tostring()`](#fn-tostring) | Return a debug-friendly string representation of the duration. | +| Function | Description | +| ----------------------------------------------- | ------------------------------------------------------------------------- | +| [`add(value, unit?)`] | Return a new duration with another duration or unit amount added. | +| [`as(unit)`] | Return the duration expressed in the requested unit. | +| [`clone()`] | Return a shallow copy of the duration value. | +| [`compare(other)`] | Compare this duration to another duration-like value. | +| [`equals(other)`] | Return `true` when both duration values have identical components. | +| [`format(pattern)`] | Format the duration using duration tokens like `Y`, `MM`, `DD`, and `HH`. | +| [`humanize(with_suffix_or_options?, options?)`] | Return a human-readable relative-style phrase for the duration. | +| [`normalize()`] | Return a compacted duration using the module's canonical carry rules. | +| [`subtract(value, unit?)`] | Return a new duration with another duration or unit amount subtracted. | +| [`to_iso()`] | Return an ISO 8601 duration string. | +| [`tostring()`] | Return a debug-friendly string representation of the duration. | **Metamethods**: -| Function | Description | -| ---------------------------------- | ------------------------------------------------------------------------------ | -| [`__call(input, unit?)`](#fn-call) | Create a duration from a numeric amount and unit. | -| [`__call(input?)`](#fn-call) | Create a duration from numeric parts, an ISO 8601 string, or another duration. | -| [`__eq(duration)`](#fn-eq) | Return `true` when both duration values have identical components. | -| [`__tostring()`](#fn-tostring) | Return the same result as `tostring()` when coerced to a string. | - - +| Function | Description | +| ------------------------ | ------------------------------------------------------------------------------ | +| [`__call(input, unit?)`] | Create a duration from a numeric amount and unit. | +| [`__call(input?)`] | Create a duration from numeric parts, an ISO 8601 string, or another duration. | +| [`__eq(duration)`] | Return `true` when both duration values have identical components. | +| [`__tostring()`] | Return the same result as `tostring()` when coerced to a string. | -### `is_duration(value)` +### `new(input, unit?)` {#new-1} -Return `true` when the value is a duration created by `mods.duration(...)` or -`mods.date.duration(...)`. +Create a duration from a numeric amount and unit. **Parameters**: -- `value` (`any`) +- `input` (`number`): Numeric amount to convert into a duration. +- `unit?` ([`mods.DateUnit`]): Unit used with the numeric amount. Defaults to + `"ms"`. -**Return**: +**Returns**: -- `isDuration` (`boolean`) +- `duration` ([`mods.Duration`]) **Example**: ```lua -local Duration = require "mods.duration" -print(Duration.is_duration(Duration({ day = 2 }))) --> true -print(Duration.is_duration({ day = 2 })) --> false +local d = Duration(90, "minute") ``` - +--- -### `new(input, unit?)` +### `new(input?)` {#new} -Create a duration from a numeric amount and unit. +Create a duration from numeric parts, an ISO 8601 string, or another duration. **Parameters**: -- `input` (`number`): Numeric amount to convert into a duration. -- `unit?` (`mods.DateUnit`): Unit used with the numeric amount. Defaults to - `"ms"`. +- `input?` (`string` | [`mods.DurationParts`] | [`mods.Duration`]): Duration + parts, an ISO 8601 string, or another duration. -**Return**: +**Returns**: -- `duration` (`mods.Duration`) +- `duration` ([`mods.Duration`]) **Example**: ```lua -local d = Duration(90, "minute") +local a = Duration({ day = 2, hour = 3 }) +local b = Duration("PT1H30M") ``` - +--- -### `new(input?)` +### `is_duration(value)` {#is-duration} -Create a duration from numeric parts, an ISO 8601 string, or another duration. +Return `true` when the value is a duration created by [`mods.duration(...)`] or +[`mods.date.duration(...)`]. **Parameters**: -- `input?` (`string|mods.DurationParts|mods.Duration`): Duration parts, an ISO - 8601 string, or another duration. +- `value` (`any`) -**Return**: +**Returns**: -- `duration` (`mods.Duration`) +- `isDuration` (`boolean`) **Example**: ```lua -local a = Duration({ day = 2, hour = 3 }) -local b = Duration("PT1H30M") +local Duration = require "mods.duration" +print(Duration.is_duration(Duration({ day = 2 }))) --> true +print(Duration.is_duration({ day = 2 })) --> false ``` -### Duration +--- - +### Duration -#### `add(value, unit?)` +#### `add(value, unit?)` {#add} Return a new duration with another duration or unit amount added. **Parameters**: -- `value` (`number|mods.DurationParts|mods.Duration`): Signed amount to add, or - another duration value. -- `unit?` (`mods.DateUnit`): Unit used when `value` is a number. +- `value` (`number` | [`mods.DurationParts`] | [`mods.Duration`]): Signed amount + to add, or another duration value. +- `unit?` ([`mods.DateUnit`]): Unit used when `value` is a number. -**Return**: +**Returns**: -- `duration` (`mods.Duration`) +- `duration` ([`mods.Duration`]) **Example**: @@ -143,17 +140,17 @@ local b = a:add(3, "hour") print(b:format("D [days] HH:mm:ss")) --> 2 days 03:00:00 ``` - +--- -#### `as(unit)` +#### `as(unit)` {#as} Return the duration expressed in the requested unit. **Parameters**: -- `unit` (`mods.DateUnit`) +- `unit` ([`mods.DateUnit`]) -**Return**: +**Returns**: - `amount` (`number`) @@ -165,15 +162,15 @@ local d = Duration({ day = 1, hour = 12 }) print(d:as("hour")) --> 36 ``` - +--- -#### `clone()` +#### `clone()` {#clone} Return a shallow copy of the duration value. -**Return**: +**Returns**: -- `duration` (`mods.Duration`) +- `duration` ([`mods.Duration`]) **Example**: @@ -184,9 +181,9 @@ local copy = d:clone() print(copy == d, rawequal(copy, d)) --> true false ``` - +--- -#### `compare(other)` +#### `compare(other)` {#compare} Compare this duration to another duration-like value. @@ -194,9 +191,9 @@ Returns `-1` when smaller, `0` when equal, and `1` when larger. **Parameters**: -- `other` (`number|string|mods.DurationParts|mods.Duration`) +- `other` (`number` | `string` | [`mods.DurationParts`] | [`mods.Duration`]) -**Return**: +**Returns**: - `ordering` (`integer`) @@ -207,9 +204,9 @@ local Duration = require "mods.duration" print(Duration({ day = 1 }):compare({ hour = 24 })) --> 0 ``` - +--- -#### `equals(other)` +#### `equals(other)` {#equals} Return `true` when both duration values have identical components. @@ -217,7 +214,7 @@ Return `true` when both duration values have identical components. - `other` (`any`): Value to compare against. -**Return**: +**Returns**: - `isEqual` (`boolean`) @@ -230,9 +227,9 @@ local b = Duration({ day = 2 }) print(a:equals(b)) --> true ``` - +--- -#### `format(pattern)` +#### `format(pattern)` {#format} Format the duration using duration tokens like `Y`, `MM`, `DD`, and `HH`. @@ -240,7 +237,7 @@ Format the duration using duration tokens like `Y`, `MM`, `DD`, and `HH`. - `pattern` (`string`): Format pattern using supported duration tokens. -**Return**: +**Returns**: - `formatted` (`string`) @@ -252,9 +249,9 @@ local d = Duration({ day = 2, hour = 3, minute = 4 }) print(d:format("D [days] HH:mm")) --> 2 days 03:04 ``` - +--- -#### `humanize(with_suffix_or_options?, options?)` +#### `humanize(with_suffix_or_options?, options?)` {#humanize} Return a human-readable relative-style phrase for the duration. @@ -264,12 +261,12 @@ output or explicit unit clamping. **Parameters**: -- `with_suffix_or_options?` (`boolean|mods.DurationHumanizeOptions`): Whether to - include `ago` / `in` style wording, or an options table. -- `options?` (`mods.DurationHumanizeOptions`): Additional options when the first - argument is a boolean. +- `with_suffix_or_options?` (`boolean` | [`mods.DurationHumanizeOptions`]): + Whether to include `ago` / `in` style wording, or an options table. +- `options?` ([`mods.DurationHumanizeOptions`]): Additional options when the + first argument is a boolean. -**Return**: +**Returns**: - `humanized` (`string`) @@ -283,15 +280,15 @@ print(d:humanize(true)) --> in 3 days print(d:humanize({ short = true })) --> 3d ``` - +--- -#### `normalize()` +#### `normalize()` {#normalize} Return a compacted duration using the module's canonical carry rules. -**Return**: +**Returns**: -- `duration` (`mods.Duration`) +- `duration` ([`mods.Duration`]) **Example**: @@ -300,21 +297,21 @@ local Duration = require "mods.duration" print(Duration({ minute = 90 }):normalize()) --> duration(hours=1, minutes=30) ``` - +--- -#### `subtract(value, unit?)` +#### `subtract(value, unit?)` {#subtract} Return a new duration with another duration or unit amount subtracted. **Parameters**: -- `value` (`number|mods.DurationParts|mods.Duration`): Signed amount to - subtract, or another duration value. -- `unit?` (`mods.DateUnit`): Unit used when `value` is a number. +- `value` (`number` | [`mods.DurationParts`] | [`mods.Duration`]): Signed amount + to subtract, or another duration value. +- `unit?` ([`mods.DateUnit`]): Unit used when `value` is a number. -**Return**: +**Returns**: -- `duration` (`mods.Duration`) +- `duration` ([`mods.Duration`]) **Example**: @@ -325,13 +322,13 @@ local b = a:subtract(3, "hour") print(b:format("D [days] HH:mm:ss")) --> 2 days 00:00:00 ``` - +--- -#### `to_iso()` +#### `to_iso()` {#to-iso} Return an ISO 8601 duration string. -**Return**: +**Returns**: - `iso` (`string`) @@ -342,13 +339,13 @@ local Duration = require "mods.duration" print(Duration({ hour = 1, minute = 30 }):to_iso()) --> PT1H30M ``` - +--- -#### `tostring()` +#### `tostring()` {#tostring} Return a debug-friendly string representation of the duration. -**Return**: +**Returns**: - `s` (`string`) @@ -359,23 +356,23 @@ local Duration = require "mods.duration" print(Duration({ day = 2, hour = 3 })) --> duration(days=2, hours=3) ``` -### Metamethods +--- - +### Metamethods -#### `__call(input, unit?)` +#### `__call(input, unit?)` {#call-1} Create a duration from a numeric amount and unit. **Parameters**: - `input` (`number`): Numeric amount to convert into a duration. -- `unit?` (`mods.DateUnit`): Unit used with the numeric amount. Defaults to +- `unit?` ([`mods.DateUnit`]): Unit used with the numeric amount. Defaults to `"ms"`. -**Return**: +**Returns**: -- `duration` (`mods.Duration`) +- `duration` ([`mods.Duration`]) **Example**: @@ -384,20 +381,20 @@ local Duration = require "mods.duration" local d = Duration(90, "minute") ``` - +--- -#### `__call(input?)` +#### `__call(input?)` {#call} Create a duration from numeric parts, an ISO 8601 string, or another duration. **Parameters**: -- `input?` (`string|mods.DurationParts|mods.Duration`): Duration parts, an ISO - 8601 string, or another duration. +- `input?` (`string` | [`mods.DurationParts`] | [`mods.Duration`]): Duration + parts, an ISO 8601 string, or another duration. -**Return**: +**Returns**: -- `duration` (`mods.Duration`) +- `duration` ([`mods.Duration`]) **Example**: @@ -407,17 +404,17 @@ local a = Duration({ day = 2, hour = 3 }) local b = Duration("PT1H30M") ``` - +--- -#### `__eq(duration)` +#### `__eq(duration)` {#eq} Return `true` when both duration values have identical components. **Parameters**: -- `duration` (`mods.Duration`): Duration to compare against. +- `duration` ([`mods.Duration`]): Duration to compare against. -**Return**: +**Returns**: - `isEqual` (`boolean`) @@ -428,13 +425,13 @@ local Duration = require "mods.duration" print(Duration({ day = 2 }) == Duration({ day = 2 })) --> true ``` - +--- -#### `__tostring()` +#### `__tostring()` {#tostring-1} Return the same result as `tostring()` when coerced to a string. -**Return**: +**Returns**: - `s` (`string`) @@ -444,3 +441,30 @@ Return the same result as `tostring()` when coerced to a string. local Duration = require "mods.duration" print(Duration({ day = 2 })) --> duration(days=2) ``` + + +[`__call(input, unit?)`]: #call-1 +[`__call(input?)`]: #call +[`__eq(duration)`]: #eq +[`__tostring()`]: #tostring-1 +[`add(value, unit?)`]: #add +[`as(unit)`]: #as +[`clone()`]: #clone +[`compare(other)`]: #compare +[`equals(other)`]: #equals +[`format(pattern)`]: #format +[`humanize(with_suffix_or_options?, options?)`]: #humanize +[`is_duration(value)`]: #is-duration +[`mods.DateUnit`]: /mods/types#mods-dateunit +[`mods.DurationHumanizeOptions`]: /mods/types#mods-durationhumanizeoptions +[`mods.DurationParts`]: /mods/types#mods-durationparts +[`mods.Duration`]: /mods/api/duration +[`mods.date.duration(...)`]: /mods/api/date#duration +[`mods.duration(...)`]: /mods/api/duration +[`new(input, unit?)`]: #new-1 +[`new(input?)`]: #new +[`normalize()`]: #normalize +[`subtract(value, unit?)`]: #subtract +[`to_iso()`]: #to-iso +[`tostring()`]: #tostring + diff --git a/docs/api/fs.md b/docs/api/fs.md index a646a9b..a522f14 100644 --- a/docs/api/fs.md +++ b/docs/api/fs.md @@ -1,20 +1,18 @@ --- +title: "fs" description: "Filesystem I/O, metadata, and filesystem path operations." --- -# `fs` - Filesystem I/O, metadata, and filesystem path operations. > [!NOTE] > -> This module requires -> [LuaFileSystem (`lfs`)](https://github.com/lunarmodules/luafilesystem). +> This module requires [LuaFileSystem (`lfs`)]. ## Usage ```lua -fs = require "mods.fs" +fs = mods.fs fs.mkdir("tmp/cache/app", true) fs.write_text("tmp/cache/app/data.txt", "hello") @@ -25,53 +23,51 @@ print(fs.read_text("tmp/cache/app/data.txt")) --> "hello" **Existence Checks**: -| Function | Description | -| ------------------------------ | ------------------------------------------------------------ | -| [`exists(path)`](#fn-exists) | Return `true` when a path exists. | -| [`lexists(path)`](#fn-lexists) | Return `true` when a path exists without following symlinks. | +| Function | Description | +| ----------------- | ------------------------------------------------------------ | +| [`exists(path)`] | Return `true` when a path exists. | +| [`lexists(path)`] | Return `true` when a path exists without following symlinks. | **Filesystem Mutations**: -| Function | Description | -| -------------------------------------------- | ----------------------------------------------------------------------------- | -| [`cd(path)`](#fn-cd) | Change the current working directory. | -| [`cp(src, dst)`](#fn-cp) | Copy a file or directory tree. | -| [`cwd()`](#fn-cwd) | Return the current working directory. | -| [`link(path, linkpath)`](#fn-link) | Create a hard link. | -| [`mkdir(path, parents?)`](#fn-mkdir) | Create a directory. | -| [`rename(oldname, newname)`](#fn-rename) | Rename or move a filesystem entry. | -| [`rm(path, recursive?)`](#fn-rm) | Remove a filesystem entry, or a directory tree when `recursive` is `true`. | -| [`symlink(path, linkpath)`](#fn-symlink) | Create a symbolic link. | -| [`touch(path)`](#fn-touch) | Create file if missing without truncating, or update timestamps if it exists. | -| [`write_bytes(path, data)`](#fn-write-bytes) | Write full file in binary mode. | -| [`write_text(path, data)`](#fn-write-text) | Write full file in text mode. | +| Function | Description | +| ---------------------------- | ----------------------------------------------------------------------------- | +| [`cd(path)`] | Change the current working directory. | +| [`cp(src, dst)`] | Copy a file or directory tree. | +| [`cwd()`] | Return the current working directory. | +| [`link(path, linkpath)`] | Create a hard link. | +| [`mkdir(path, parents?)`] | Create a directory. | +| [`rename(oldname, newname)`] | Rename or move a filesystem entry. | +| [`rm(path, recursive?)`] | Remove a filesystem entry, or a directory tree when `recursive` is `true`. | +| [`symlink(path, linkpath)`] | Create a symbolic link. | +| [`touch(path)`] | Create file if missing without truncating, or update timestamps if it exists. | +| [`write_bytes(path, data)`] | Write full file in binary mode. | +| [`write_text(path, data)`] | Write full file in text mode. | **Metadata**: -| Function | Description | -| -------------------------------- | ---------------------------------------------------------------------------------- | -| [`getatime(path)`](#fn-getatime) | Return last access time. | -| [`getctime(path)`](#fn-getctime) | Return metadata change time. | -| [`getmtime(path)`](#fn-getmtime) | Return last modification time. | -| [`getsize(path)`](#fn-getsize) | Return file size in bytes. | -| [`lstat(path)`](#fn-lstat) | Return symlink-aware file attributes. | -| [`samefile(a, b)`](#fn-samefile) | Return whether two paths refer to the same file, or `nil` and an error on failure. | -| [`stat(path)`](#fn-stat) | Return file attributes. | +| Function | Description | +| ------------------ | ---------------------------------------------------------------------------------- | +| [`getatime(path)`] | Return last access time. | +| [`getctime(path)`] | Return metadata change time. | +| [`getmtime(path)`] | Return last modification time. | +| [`getsize(path)`] | Return file size in bytes. | +| [`lstat(path)`] | Return symlink-aware file attributes. | +| [`samefile(a, b)`] | Return whether two paths refer to the same file, or `nil` and an error on failure. | +| [`stat(path)`] | Return file attributes. | **Reading**: -| Function | Description | -| ------------------------------------- | -------------------------------------- | -| [`dir(path, opts?)`](#fn-dir) | Iterator over items in `path`. | -| [`listdir(path, opts?)`](#fn-listdir) | Return direct children of a directory. | -| [`read_bytes(path)`](#fn-read-bytes) | Read full file in binary mode. | -| [`read_text(path)`](#fn-read-text) | Read full file in text mode. | +| Function | Description | +| ------------------------ | -------------------------------------- | +| [`dir(path, opts?)`] | Iterator over items in `path`. | +| [`listdir(path, opts?)`] | Return direct children of a directory. | +| [`read_bytes(path)`] | Read full file in binary mode. | +| [`read_text(path)`] | Read full file in text mode. | ### Existence Checks - - -#### `exists(path)` +#### `exists(path)` {#exists} Return `true` when a path exists. @@ -79,7 +75,7 @@ Return `true` when a path exists. - `path` (`string`): Input path. -**Return**: +**Returns**: - `exists` (`boolean`): True when the path exists. @@ -93,9 +89,9 @@ fs.exists("README.md") --> true > > Broken symlinks return `false`. - +--- -#### `lexists(path)` +#### `lexists(path)` {#lexists} Return `true` when a path exists without following symlinks. @@ -103,7 +99,7 @@ Return `true` when a path exists without following symlinks. - `path` (`string`): Input path. -**Return**: +**Returns**: - `exists` (`boolean`): True when the path or symlink entry exists. @@ -117,11 +113,11 @@ fs.lexists("README.md") --> true > > Broken symlinks return `true`. -### Filesystem Mutations +--- - +### Filesystem Mutations -#### `cd(path)` +#### `cd(path)` {#cd} Change the current working directory. @@ -129,11 +125,11 @@ Change the current working directory. - `path` (`string`): Directory path to switch into. -**Return**: +**Returns**: -- `changed` (`true?`): `true` when the directory change succeeds, or `nil` on +- `changed?` (`true`): `true` when the directory change succeeds, or `nil` on failure. -- `errmsg` (`string?`): Error message when the change fails. +- `errmsg?` (`string`): Error message when the change fails. **Example**: @@ -141,9 +137,9 @@ Change the current working directory. fs.cd("src") ``` - +--- -#### `cp(src, dst)` +#### `cp(src, dst)` {#cp} Copy a file or directory tree. @@ -152,11 +148,11 @@ Copy a file or directory tree. - `src` (`string`): Source path. - `dst` (`string`): Destination path. -**Return**: +**Returns**: -- `copied` (`true?`): `true` when copying succeeds, or `nil` on failure. -- `errmsg` (`string?`): Error message when the check fails. -- `errcode` (`integer?`): OS error code when available. +- `copied?` (`true`): `true` when copying succeeds, or `nil` on failure. +- `errmsg?` (`string`): Error message when the check fails. +- `errcode?` (`integer`): OS error code when available. **Example**: @@ -165,17 +161,17 @@ fs.cp("a.txt", "b.txt") fs.cp("src", "backup/src") ``` - +--- -#### `cwd()` +#### `cwd()` {#cwd} Return the current working directory. -**Return**: +**Returns**: -- `cwd` (`string?`): Current working directory, or `nil` on failure. -- `errmsg` (`string?`): Error message when the lookup fails. -- `errcode` (`integer?`): OS error code when available. +- `cwd?` (`string`): Current working directory, or `nil` on failure. +- `errmsg?` (`string`): Error message when the lookup fails. +- `errcode?` (`integer`): OS error code when available. **Example**: @@ -183,9 +179,9 @@ Return the current working directory. fs.cwd() ``` - +--- -#### `link(path, linkpath)` +#### `link(path, linkpath)` {#link} Create a hard link. @@ -194,11 +190,11 @@ Create a hard link. - `path` (`string`): Existing path to link to. - `linkpath` (`string`): New link path to create. -**Return**: +**Returns**: -- `linked` (`true?`): `true` when link creation succeeds, or `nil` on failure. -- `errmsg` (`string?`): Error message when the check fails. -- `errcode` (`integer?`): OS error code when available. +- `linked?` (`true`): `true` when link creation succeeds, or `nil` on failure. +- `errmsg?` (`string`): Error message when the check fails. +- `errcode?` (`integer`): OS error code when available. **Example**: @@ -206,9 +202,9 @@ Create a hard link. fs.link("target.txt", "hardlink.txt") ``` - +--- -#### `mkdir(path, parents?)` +#### `mkdir(path, parents?)` {#mkdir} Create a directory. @@ -217,12 +213,12 @@ Create a directory. - `path` (`string`): Input path. - `parents?` (`boolean`): Create missing parent directories when `true`. -**Return**: +**Returns**: -- `created` (`true?`): `true` when directory creation succeeds, or `nil` on +- `created?` (`true`): `true` when directory creation succeeds, or `nil` on failure. -- `errmsg` (`string?`): Error message when the check fails. -- `errcode` (`integer?`): OS error code when available. +- `errmsg?` (`string`): Error message when the check fails. +- `errcode?` (`integer`): OS error code when available. **Example**: @@ -230,9 +226,9 @@ Create a directory. fs.mkdir("tmp/a/b", true) ``` - +--- -#### `rename(oldname, newname)` +#### `rename(oldname, newname)` {#rename} Rename or move a filesystem entry. @@ -241,11 +237,11 @@ Rename or move a filesystem entry. - `oldname` (`string`): Existing path. - `newname` (`string`): Replacement path. -**Return**: +**Returns**: -- `renamed` (`true?`): `true` when the rename succeeds, or `nil` on failure. -- `errmsg` (`string?`): Error message when the check fails. -- `errcode` (`integer?`): OS error code when available. +- `renamed?` (`true`): `true` when the rename succeeds, or `nil` on failure. +- `errmsg?` (`string`): Error message when the check fails. +- `errcode?` (`integer`): OS error code when available. **Example**: @@ -257,9 +253,9 @@ fs.rename("old.txt", "new.txt") > > This is an alias for `os.rename`. - +--- -#### `rm(path, recursive?)` +#### `rm(path, recursive?)` {#rm} Remove a filesystem entry, or a directory tree when `recursive` is `true`. @@ -268,11 +264,11 @@ Remove a filesystem entry, or a directory tree when `recursive` is `true`. - `path` (`string`): Input path. - `recursive?` (`boolean`): Remove a directory tree recursively when `true`. -**Return**: +**Returns**: -- `removed` (`true?`): `true` when removal succeeds, or `nil` on failure. -- `errmsg` (`string?`): Error message when the check fails. -- `errcode` (`integer?`): OS error code when available. +- `removed?` (`true`): `true` when removal succeeds, or `nil` on failure. +- `errmsg?` (`string`): Error message when the check fails. +- `errcode?` (`integer`): OS error code when available. **Example**: @@ -281,9 +277,9 @@ fs.rm("tmp.txt") --> true, nil fs.rm("tmp/cache", true) --> true, nil ``` - +--- -#### `symlink(path, linkpath)` +#### `symlink(path, linkpath)` {#symlink} Create a symbolic link. @@ -292,11 +288,11 @@ Create a symbolic link. - `path` (`string`): Path to reference from the new symlink. - `linkpath` (`string`): New symlink path to create. -**Return**: +**Returns**: -- `linked` (`true?`): `true` when link creation succeeds, or `nil` on failure. -- `errmsg` (`string?`): Error message when the check fails. -- `errcode` (`integer?`): OS error code when available. +- `linked?` (`true`): `true` when link creation succeeds, or `nil` on failure. +- `errmsg?` (`string`): Error message when the check fails. +- `errcode?` (`integer`): OS error code when available. **Example**: @@ -304,9 +300,9 @@ Create a symbolic link. fs.symlink("target.txt", "symlink.txt") ``` - +--- -#### `touch(path)` +#### `touch(path)` {#touch} Create file if missing without truncating, or update timestamps if it exists. @@ -314,12 +310,12 @@ Create file if missing without truncating, or update timestamps if it exists. - `path` (`string`): Input path. -**Return**: +**Returns**: -- `touched` (`true?`): `true` when the file exists after touch, or `nil` on +- `touched?` (`true`): `true` when the file exists after touch, or `nil` on failure. -- `errmsg` (`string?`): Error message when the check fails. -- `errcode` (`integer?`): OS error code when available. +- `errmsg?` (`string`): Error message when the check fails. +- `errcode?` (`integer`): OS error code when available. **Example**: @@ -327,9 +323,9 @@ Create file if missing without truncating, or update timestamps if it exists. fs.touch("tmp.txt") --> true, nil ``` - +--- -#### `write_bytes(path, data)` +#### `write_bytes(path, data)` {#write-bytes} Write full file in binary mode. @@ -338,11 +334,11 @@ Write full file in binary mode. - `path` (`string`): Input path. - `data` (`string`): Input data. -**Return**: +**Returns**: -- `written` (`true?`): `true` when writing succeeds, or `nil` on failure. -- `errmsg` (`string?`): Error message when the check fails. -- `errcode` (`integer?`): OS error code when available. +- `written?` (`true`): `true` when writing succeeds, or `nil` on failure. +- `errmsg?` (`string`): Error message when the check fails. +- `errcode?` (`integer`): OS error code when available. **Example**: @@ -350,9 +346,9 @@ Write full file in binary mode. fs.write_bytes("tmp.bin", "abc") --> true, nil ``` - +--- -#### `write_text(path, data)` +#### `write_text(path, data)` {#write-text} Write full file in text mode. @@ -361,11 +357,11 @@ Write full file in text mode. - `path` (`string`): Input path. - `data` (`string`): Input data. -**Return**: +**Returns**: -- `written` (`true?`): `true` when writing succeeds, or `nil` on failure. -- `errmsg` (`string?`): Error message when the check fails. -- `errcode` (`integer?`): OS error code when available. +- `written?` (`true`): `true` when writing succeeds, or `nil` on failure. +- `errmsg?` (`string`): Error message when the check fails. +- `errcode?` (`integer`): OS error code when available. **Example**: @@ -373,11 +369,11 @@ Write full file in text mode. fs.write_text("tmp.txt", "abc") --> true, nil ``` -### Metadata +--- - +### Metadata -#### `getatime(path)` +#### `getatime(path)` {#getatime} Return last access time. @@ -385,11 +381,11 @@ Return last access time. - `path` (`string`): Input path. -**Return**: +**Returns**: -- `timestamp` (`number?`): Access time (seconds since epoch). -- `errmsg` (`string?`): Error message when the check fails. -- `errcode` (`integer?`): OS error code when available. +- `timestamp?` (`number`): Access time (seconds since epoch). +- `errmsg?` (`string`): Error message when the check fails. +- `errcode?` (`integer`): OS error code when available. **Example**: @@ -397,9 +393,9 @@ Return last access time. fs.getatime("README.md") --> 1712345678 ``` - +--- -#### `getctime(path)` +#### `getctime(path)` {#getctime} Return metadata change time. @@ -407,11 +403,11 @@ Return metadata change time. - `path` (`string`): Input path. -**Return**: +**Returns**: -- `timestamp` (`number?`): Change time (seconds since epoch). -- `errmsg` (`string?`): Error message when the check fails. -- `errcode` (`integer?`): OS error code when available. +- `timestamp?` (`number`): Change time (seconds since epoch). +- `errmsg?` (`string`): Error message when the check fails. +- `errcode?` (`integer`): OS error code when available. **Example**: @@ -419,9 +415,9 @@ Return metadata change time. fs.getctime("README.md") --> 1712345678 ``` - +--- -#### `getmtime(path)` +#### `getmtime(path)` {#getmtime} Return last modification time. @@ -429,11 +425,11 @@ Return last modification time. - `path` (`string`): Input path. -**Return**: +**Returns**: -- `timestamp` (`number?`): Modification time (seconds since epoch). -- `errmsg` (`string?`): Error message when the check fails. -- `errcode` (`integer?`): OS error code when available. +- `timestamp?` (`number`): Modification time (seconds since epoch). +- `errmsg?` (`string`): Error message when the check fails. +- `errcode?` (`integer`): OS error code when available. **Example**: @@ -441,9 +437,9 @@ Return last modification time. fs.getmtime("README.md") --> 1712345678 ``` - +--- -#### `getsize(path)` +#### `getsize(path)` {#getsize} Return file size in bytes. @@ -451,11 +447,11 @@ Return file size in bytes. - `path` (`string`): Input path. -**Return**: +**Returns**: -- `size` (`integer?`): File size in bytes. -- `errmsg` (`string?`): Error message when the check fails. -- `errcode` (`integer?`): OS error code when available. +- `size?` (`integer`): File size in bytes. +- `errmsg?` (`string`): Error message when the check fails. +- `errcode?` (`integer`): OS error code when available. **Example**: @@ -463,9 +459,9 @@ Return file size in bytes. fs.getsize("README.md") --> 1234 ``` - +--- -#### `lstat(path)` +#### `lstat(path)` {#lstat} Return symlink-aware file attributes. @@ -473,12 +469,12 @@ Return symlink-aware file attributes. - `path` (`string`): Input path. -**Return**: +**Returns**: -- `attrs` (`LuaFileSystem.Attributes?`): Symlink-aware attributes, or `nil` on +- `attrs?` (`LuaFileSystem.Attributes`): Symlink-aware attributes, or `nil` on failure. -- `errmsg` (`string?`): Error message when the check fails. -- `errcode` (`integer?`): OS error code when available. +- `errmsg?` (`string`): Error message when the check fails. +- `errcode?` (`integer`): OS error code when available. **Example**: @@ -486,9 +482,9 @@ Return symlink-aware file attributes. fs.lstat("README.md") ``` - +--- -#### `samefile(a, b)` +#### `samefile(a, b)` {#samefile} Return whether two paths refer to the same file, or `nil` and an error on failure. @@ -498,11 +494,11 @@ failure. - `a` (`string`): Input path. - `b` (`string`): Input path. -**Return**: +**Returns**: -- `isSameFile` (`boolean?`): True when both paths refer to the same file. -- `errmsg` (`string?`): Error message when the check fails. -- `errcode` (`integer?`): OS error code when available. +- `isSameFile?` (`boolean`): True when both paths refer to the same file. +- `errmsg?` (`string`): Error message when the check fails. +- `errcode?` (`integer`): OS error code when available. **Example**: @@ -510,9 +506,9 @@ failure. fs.samefile("README.md", "README.md") --> true ``` - +--- -#### `stat(path)` +#### `stat(path)` {#stat} Return file attributes. @@ -520,13 +516,12 @@ Return file attributes. - `path` (`string`): Input path. -**Return**: +**Returns**: -- `attrs` - (`string|integer|LuaFileSystem.AttributeMode|LuaFileSystem.Attributes?`): File - attributes, or `nil` on failure. -- `errmsg` (`string?`): Error message when the check fails. -- `errcode` (`integer?`): OS error code when available. +- `attrs?` (`string` | `integer` | `LuaFileSystem.AttributeMode` | + `LuaFileSystem.Attributes`): File attributes, or `nil` on failure. +- `errmsg?` (`string`): Error message when the check fails. +- `errcode?` (`integer`): OS error code when available. **Example**: @@ -534,11 +529,11 @@ Return file attributes. fs.stat("README.md") ``` -### Reading +--- - +### Reading -#### `dir(path, opts?)` +#### `dir(path, opts?)` {#dir} Iterator over items in `path`. @@ -554,15 +549,15 @@ Iterator over items in `path`. - `path` (`string`): Input path. - `opts?` - (`{hidden?:boolean, recursive?:boolean, follow?:boolean, type?:modsFsEntryType}`): + (`{hidden?:boolean, recursive?:boolean, follow?:boolean, type?:`[`mods.FsEntryType`]`}`): Optional traversal options. -**Return**: +**Returns**: -- `iterator` - (`(fun(state:table, prev?:string):basename:string?, type:modsFsEntryType?)?`): +- `iterator?` + (`(fun(state:table, prev?:string):basename?: string, type?: `[`mods.FsEntryType`]`)`): Iterator, or `nil` on failure. -- `state` (`table|string`): Iterator state on success, or error message on +- `state` (`table` | `string`): Iterator state on success, or error message on failure. **Example**: @@ -573,9 +568,9 @@ for name, type in fs.dir(path.cwd(), { recursive = true }) do end ``` - +--- -#### `listdir(path, opts?)` +#### `listdir(path, opts?)` {#listdir} Return direct children of a directory. @@ -592,14 +587,14 @@ Return direct children of a directory. - `path` (`string`): Input path. - `opts?` - (`{hidden?:boolean, recursive?:boolean, follow?:boolean, type?:modsFsEntryType, names?:boolean}`): + (`{hidden?:boolean, recursive?:boolean, follow?:boolean, type?:`[`mods.FsEntryType`]`, names?:boolean}`): Optional traversal options. -**Return**: +**Returns**: -- `paths` (`mods.List?`): Direct child paths, or basenames when +- `paths?` ([`mods.List`]``): Direct child paths, or basenames when `opts.names` is `true`. -- `err` (`string?`): Error message when traversal setup fails. +- `err?` (`string`): Error message when traversal setup fails. **Example**: @@ -608,9 +603,9 @@ fs.listdir("src") fs.listdir("src", { names = true }) ``` - +--- -#### `read_bytes(path)` +#### `read_bytes(path)` {#read-bytes} Read full file in binary mode. @@ -618,11 +613,11 @@ Read full file in binary mode. - `path` (`string`): Input path. -**Return**: +**Returns**: -- `body` (`string?`): File contents read in binary mode, or `nil` on failure. -- `errmsg` (`string?`): Error message when the check fails. -- `errcode` (`integer?`): OS error code when available. +- `body?` (`string`): File contents read in binary mode, or `nil` on failure. +- `errmsg?` (`string`): Error message when the check fails. +- `errcode?` (`integer`): OS error code when available. **Example**: @@ -630,9 +625,9 @@ Read full file in binary mode. fs.read_bytes("README.md") ``` - +--- -#### `read_text(path)` +#### `read_text(path)` {#read-text} Read full file in text mode. @@ -640,14 +635,44 @@ Read full file in text mode. - `path` (`string`): Input path. -**Return**: +**Returns**: -- `body` (`string?`): File contents read in text mode, or `nil` on failure. -- `errmsg` (`string?`): Error message when the check fails. -- `errcode` (`integer?`): OS error code when available. +- `body?` (`string`): File contents read in text mode, or `nil` on failure. +- `errmsg?` (`string`): Error message when the check fails. +- `errcode?` (`integer`): OS error code when available. **Example**: ```lua fs.read_text("README.md") ``` + + +[LuaFileSystem (`lfs`)]: https://github.com/lunarmodules/luafilesystem +[`cd(path)`]: #cd +[`cp(src, dst)`]: #cp +[`cwd()`]: #cwd +[`dir(path, opts?)`]: #dir +[`exists(path)`]: #exists +[`getatime(path)`]: #getatime +[`getctime(path)`]: #getctime +[`getmtime(path)`]: #getmtime +[`getsize(path)`]: #getsize +[`lexists(path)`]: #lexists +[`link(path, linkpath)`]: #link +[`listdir(path, opts?)`]: #listdir +[`lstat(path)`]: #lstat +[`mkdir(path, parents?)`]: #mkdir +[`mods.FsEntryType`]: /mods/types#mods-fsentrytype +[`mods.List`]: /mods/api/list +[`read_bytes(path)`]: #read-bytes +[`read_text(path)`]: #read-text +[`rename(oldname, newname)`]: #rename +[`rm(path, recursive?)`]: #rm +[`samefile(a, b)`]: #samefile +[`stat(path)`]: #stat +[`symlink(path, linkpath)`]: #symlink +[`touch(path)`]: #touch +[`write_bytes(path, data)`]: #write-bytes +[`write_text(path, data)`]: #write-text + diff --git a/docs/api/glob.md b/docs/api/glob.md index 045a163..2599aaa 100644 --- a/docs/api/glob.md +++ b/docs/api/glob.md @@ -1,15 +1,14 @@ --- +title: "glob" description: "Glob-style matching and filesystem expansion helpers." --- -# `glob` - Glob-style matching and filesystem expansion helpers. ## Usage ```lua -glob = require "mods.glob" +glob = mods.glob print(glob.match("src/mods/fs.lua", "**/*.lua")) --> true print(glob.match("DATA.TXT", "*.txt", true)) --> true @@ -59,21 +58,19 @@ print(glob.glob("src", "*.lua")[1]) **Glob Operations**: -| Function | Description | -| --------------------------------------------------- | ----------------------------------------------------------- | -| [`escape(s)`](#fn-escape) | Escape glob metacharacters in a literal string. | -| [`filter(names, pattern, ignorecase?)`](#fn-filter) | Return the values from `names` that match the glob pattern. | -| [`glob(path, pattern?, opts?)`](#fn-glob) | Return glob matches under `path`. | -| [`has_magic(s)`](#fn-has-magic) | Return whether a pattern contains glob metacharacters. | -| [`iglob(path, pattern?, opts?)`](#fn-iglob) | Iterator over glob matches under `path`. | -| [`match(path, pattern, ignorecase?)`](#fn-match) | Match a path against a glob pattern. | -| [`translate(pattern)`](#fn-translate) | Translate one glob segment into an equivalent Lua pattern. | +| Function | Description | +| --------------------------------------- | ----------------------------------------------------------- | +| [`escape(s)`] | Escape glob metacharacters in a literal string. | +| [`filter(names, pattern, ignorecase?)`] | Return the values from `names` that match the glob pattern. | +| [`glob(path, pattern?, opts?)`] | Return glob matches under `path`. | +| [`has_magic(s)`] | Return whether a pattern contains glob metacharacters. | +| [`iglob(path, pattern?, opts?)`] | Iterator over glob matches under `path`. | +| [`match(path, pattern, ignorecase?)`] | Match a path against a glob pattern. | +| [`translate(pattern)`] | Translate one glob segment into an equivalent Lua pattern. | ### Glob Operations - - -#### `escape(s)` +#### `escape(s)` {#escape} Escape glob metacharacters in a literal string. @@ -81,7 +78,7 @@ Escape glob metacharacters in a literal string. - `s` (`string`): Input literal string. -**Return**: +**Returns**: - `pattern` (`string`): Escaped glob pattern. @@ -91,9 +88,9 @@ Escape glob metacharacters in a literal string. glob.escape("a*b") --> "a\\*b" ``` - +--- -#### `filter(names, pattern, ignorecase?)` +#### `filter(names, pattern, ignorecase?)` {#filter} Return the values from `names` that match the glob pattern. @@ -103,9 +100,9 @@ Return the values from `names` that match the glob pattern. - `pattern` (`string`): Input glob pattern. - `ignorecase?` (`boolean`): Override platform-default case matching. -**Return**: +**Returns**: -- `matches` (`mods.List`): Matching values from `names`. +- `matches` ([`mods.List`]``): Matching values from `names`. **Example**: @@ -113,9 +110,9 @@ Return the values from `names` that match the glob pattern. glob.filter({ "a.lua", "b.txt", "c.lua" }, "*.lua") --> { "a.lua", "c.lua" } ``` - +--- -#### `glob(path, pattern?, opts?)` +#### `glob(path, pattern?, opts?)` {#glob} Return glob matches under `path`. @@ -130,13 +127,11 @@ Return glob matches under `path`. - `path` (`string`): Input path. - `pattern?` (`string`): Optional pattern to match. -- `opts?` - (`{hidden?:boolean, recursive?:boolean, follow?:boolean, ignorecase?:boolean}`): - Optional glob options. +- `opts?` ([`mods.GlobOptions`]): Optional glob options. -**Return**: +**Returns**: -- `paths` (`mods.List`): Matching paths under `path`. +- `paths` ([`mods.List`]``): Matching paths under `path`. **Example**: @@ -145,9 +140,9 @@ glob.glob("src", "*.lua") glob.glob("src", "*.lua", { recursive = true }) ``` - +--- -#### `has_magic(s)` +#### `has_magic(s)` {#has-magic} Return whether a pattern contains glob metacharacters. @@ -155,7 +150,7 @@ Return whether a pattern contains glob metacharacters. - `s` (`string`): Input string. -**Return**: +**Returns**: - `has_magic` (`boolean`): True when the string contains glob syntax. @@ -166,9 +161,9 @@ glob.has_magic("foo.txt") --> false glob.has_magic("*.txt") --> true ``` - +--- -#### `iglob(path, pattern?, opts?)` +#### `iglob(path, pattern?, opts?)` {#iglob} Iterator over glob matches under `path`. @@ -183,13 +178,11 @@ Iterator over glob matches under `path`. - `path` (`string`): Input path. - `pattern?` (`string`): Optional pattern to match. -- `opts?` - (`{hidden?:boolean, recursive?:boolean, follow?:boolean, ignorecase?:boolean}`): - Optional glob options. +- `opts?` ([`mods.GlobOptions`]): Optional glob options. -**Return**: +**Returns**: -- `iterator` (`(fun(state:table, prev?:string): (path:string?))`): Iterator +- `iterator` (`(fun(state:table, prev?:string): (path?: string))`): Iterator function. - `state` (`table`): Iterator state table. - `initial` (`nil`): Initial iterator value. @@ -202,9 +195,9 @@ for path in glob.iglob("src", "*.lua") do end ``` - +--- -#### `match(path, pattern, ignorecase?)` +#### `match(path, pattern, ignorecase?)` {#match} Match a path against a glob pattern. @@ -214,7 +207,7 @@ Match a path against a glob pattern. - `pattern` (`string`): Input glob pattern. - `ignorecase?` (`boolean`): Override platform-default case matching. -**Return**: +**Returns**: - `matches` (`boolean`): True when the path matches the pattern. @@ -224,9 +217,9 @@ Match a path against a glob pattern. glob.match("src/mods/fs.lua", "**/*.lua") --> true ``` - +--- -#### `translate(pattern)` +#### `translate(pattern)` {#translate} Translate one glob segment into an equivalent Lua pattern. @@ -234,7 +227,7 @@ Translate one glob segment into an equivalent Lua pattern. - `pattern` (`string`): Input glob segment. -**Return**: +**Returns**: - `lua_pattern` (`string`): Lua pattern string. @@ -265,3 +258,15 @@ print(matches == translated_matches) --> true > print(("src/x.lua"):match(glob.translate(pattern))) --> nil > print(glob.match("src/x.lua", pattern)) --> true > ``` + + +[`escape(s)`]: #escape +[`filter(names, pattern, ignorecase?)`]: #filter +[`glob(path, pattern?, opts?)`]: #glob +[`has_magic(s)`]: #has-magic +[`iglob(path, pattern?, opts?)`]: #iglob +[`match(path, pattern, ignorecase?)`]: #match +[`mods.GlobOptions`]: /mods/types#mods-globoptions +[`mods.List`]: /mods/api/list +[`translate(pattern)`]: #translate + diff --git a/docs/api/is.md b/docs/api/is.md index 0505cbd..4889086 100644 --- a/docs/api/is.md +++ b/docs/api/is.md @@ -1,15 +1,14 @@ --- +title: "is" description: "Type predicates for Lua values and filesystem path types." --- -# `is` - Type predicates for Lua values and filesystem path types. ## Usage ```lua -is = require "mods.is" +is = mods.is ok = is.number(3.14) --> true ok = is("hello", "string") --> true @@ -30,9 +29,8 @@ ok = is.table({}) --> true > [!IMPORTANT] > -> Path checks require **LuaFileSystem** -> ([`lfs`](https://github.com/lunarmodules/luafilesystem)) and raise an error if -> it is not installed. +> Path checks require **LuaFileSystem** ([`lfs`]) and raise an error if it is +> not installed. @@ -51,47 +49,45 @@ is("hello", "STRING") --> true **Path Checks**: -| Function | Description | -| ------------------------- | ------------------------------------------------------------ | -| [`block(v)`](#fn-block) | Returns `true` when `v` is a block device path. | -| [`char(v)`](#fn-char) | Returns `true` when `v` is a character device path. | -| [`device(v)`](#fn-device) | Returns `true` when `v` is a block or character device path. | -| [`dir(v)`](#fn-dir) | Returns `true` when `v` is a directory path. | -| [`fifo(v)`](#fn-fifo) | Returns `true` when `v` is a FIFO path. | -| [`file(v)`](#fn-file) | Returns `true` when `v` is a file path. | -| [`link(v)`](#fn-link) | Returns `true` when `v` is a symlink path. | -| [`path(v)`](#fn-path) | Returns `true` when `v` is a valid filesystem path. | -| [`socket(v)`](#fn-socket) | Returns `true` when `v` is a socket path. | +| Function | Description | +| ------------- | ------------------------------------------------------------ | +| [`block(v)`] | Returns `true` when `v` is a block device path. | +| [`char(v)`] | Returns `true` when `v` is a character device path. | +| [`device(v)`] | Returns `true` when `v` is a block or character device path. | +| [`dir(v)`] | Returns `true` when `v` is a directory path. | +| [`fifo(v)`] | Returns `true` when `v` is a FIFO path. | +| [`file(v)`] | Returns `true` when `v` is a file path. | +| [`link(v)`] | Returns `true` when `v` is a symlink path. | +| [`path(v)`] | Returns `true` when `v` is a valid filesystem path. | +| [`socket(v)`] | Returns `true` when `v` is a socket path. | **Type Checks**: -| Function | Description | -| ----------------------------- | -------------------------------------- | -| [`boolean(v)`](#fn-boolean) | Returns `true` when `v` is a boolean. | -| [`function(v)`](#fn-function) | Returns `true` when `v` is a function. | -| [`nil(v)`](#fn-nil) | Returns `true` when `v` is `nil`. | -| [`number(v)`](#fn-number) | Returns `true` when `v` is a number. | -| [`string(v)`](#fn-string) | Returns `true` when `v` is a string. | -| [`table(v)`](#fn-table) | Returns `true` when `v` is a table. | -| [`thread(v)`](#fn-thread) | Returns `true` when `v` is a thread. | -| [`userdata(v)`](#fn-userdata) | Returns `true` when `v` is userdata. | +| Function | Description | +| --------------- | -------------------------------------- | +| [`boolean(v)`] | Returns `true` when `v` is a boolean. | +| [`function(v)`] | Returns `true` when `v` is a function. | +| [`nil(v)`] | Returns `true` when `v` is `nil`. | +| [`number(v)`] | Returns `true` when `v` is a number. | +| [`string(v)`] | Returns `true` when `v` is a string. | +| [`table(v)`] | Returns `true` when `v` is a table. | +| [`thread(v)`] | Returns `true` when `v` is a thread. | +| [`userdata(v)`] | Returns `true` when `v` is userdata. | **Value Checks**: -| Function | Description | -| ----------------------------- | ------------------------------------------- | -| [`callable(v)`](#fn-callable) | Returns `true` when `v` is callable. | -| [`false(v)`](#fn-false) | Returns `true` when `v` is exactly `false`. | -| [`falsy(v)`](#fn-falsy) | Returns `true` when `v` is falsy. | -| [`integer(v)`](#fn-integer) | Returns `true` when `v` is an integer. | -| [`true(v)`](#fn-true) | Returns `true` when `v` is exactly `true`. | -| [`truthy(v)`](#fn-truthy) | Returns `true` when `v` is truthy. | +| Function | Description | +| --------------- | ------------------------------------------- | +| [`callable(v)`] | Returns `true` when `v` is callable. | +| [`false(v)`] | Returns `true` when `v` is exactly `false`. | +| [`falsy(v)`] | Returns `true` when `v` is falsy. | +| [`integer(v)`] | Returns `true` when `v` is an integer. | +| [`true(v)`] | Returns `true` when `v` is exactly `true`. | +| [`truthy(v)`] | Returns `true` when `v` is truthy. | ### Path Checks - - -#### `block(v)` +#### `block(v)` {#block} Returns `true` when `v` is a block device path. @@ -99,7 +95,7 @@ Returns `true` when `v` is a block device path. - `v` (`any`): Value to validate. -**Return**: +**Returns**: - `isBlock` (`boolean`): Whether the check succeeds. @@ -109,9 +105,9 @@ Returns `true` when `v` is a block device path. is.block("/dev/sda") ``` - +--- -#### `char(v)` +#### `char(v)` {#char} Returns `true` when `v` is a character device path. @@ -119,7 +115,7 @@ Returns `true` when `v` is a character device path. - `v` (`any`): Value to validate. -**Return**: +**Returns**: - `isChar` (`boolean`): Whether the check succeeds. @@ -129,9 +125,9 @@ Returns `true` when `v` is a character device path. is.char("/dev/null") ``` - +--- -#### `device(v)` +#### `device(v)` {#device} Returns `true` when `v` is a block or character device path. @@ -139,7 +135,7 @@ Returns `true` when `v` is a block or character device path. - `v` (`any`): Value to validate. -**Return**: +**Returns**: - `isDevice` (`boolean`): Whether the check succeeds. @@ -149,9 +145,9 @@ Returns `true` when `v` is a block or character device path. is.device("/dev/null") ``` - +--- -#### `dir(v)` +#### `dir(v)` {#dir} Returns `true` when `v` is a directory path. @@ -159,7 +155,7 @@ Returns `true` when `v` is a directory path. - `v` (`any`): Value to validate. -**Return**: +**Returns**: - `isDir` (`boolean`): Whether the check succeeds. @@ -169,9 +165,9 @@ Returns `true` when `v` is a directory path. is.dir("/tmp") ``` - +--- -#### `fifo(v)` +#### `fifo(v)` {#fifo} Returns `true` when `v` is a FIFO path. @@ -179,7 +175,7 @@ Returns `true` when `v` is a FIFO path. - `v` (`any`): Value to validate. -**Return**: +**Returns**: - `isFifo` (`boolean`): Whether the check succeeds. @@ -189,9 +185,9 @@ Returns `true` when `v` is a FIFO path. is.fifo("/path/to/fifo") ``` - +--- -#### `file(v)` +#### `file(v)` {#file} Returns `true` when `v` is a file path. @@ -199,7 +195,7 @@ Returns `true` when `v` is a file path. - `v` (`any`): Value to validate. -**Return**: +**Returns**: - `isFile` (`boolean`): Whether the check succeeds. @@ -209,9 +205,9 @@ Returns `true` when `v` is a file path. is.file("README.md") ``` - +--- -#### `link(v)` +#### `link(v)` {#link} Returns `true` when `v` is a symlink path. @@ -219,7 +215,7 @@ Returns `true` when `v` is a symlink path. - `v` (`any`): Value to validate. -**Return**: +**Returns**: - `isLink` (`boolean`): Whether the check succeeds. @@ -229,9 +225,9 @@ Returns `true` when `v` is a symlink path. is.link("/path/to/link") ``` - +--- -#### `path(v)` +#### `path(v)` {#path} Returns `true` when `v` is a valid filesystem path. @@ -239,7 +235,7 @@ Returns `true` when `v` is a valid filesystem path. - `v` (`any`): Value to validate. -**Return**: +**Returns**: - `isPath` (`boolean`): Whether the check succeeds. @@ -253,9 +249,9 @@ is.path("README.md") > > Returns `true` for broken symlinks. - +--- -#### `socket(v)` +#### `socket(v)` {#socket} Returns `true` when `v` is a socket path. @@ -263,7 +259,7 @@ Returns `true` when `v` is a socket path. - `v` (`any`): Value to validate. -**Return**: +**Returns**: - `isSocket` (`boolean`): Whether the check succeeds. @@ -273,11 +269,11 @@ Returns `true` when `v` is a socket path. is.socket("/path/to/socket") ``` -### Type Checks +--- - +### Type Checks -#### `boolean(v)` +#### `boolean(v)` {#boolean} Returns `true` when `v` is a boolean. @@ -285,7 +281,7 @@ Returns `true` when `v` is a boolean. - `v` (`any`): Value to validate. -**Return**: +**Returns**: - `isBoolean` (`boolean`): Whether the check succeeds. @@ -295,9 +291,9 @@ Returns `true` when `v` is a boolean. is.boolean(true) ``` - +--- -#### `function(v)` +#### `function(v)` {#function} Returns `true` when `v` is a function. @@ -305,7 +301,7 @@ Returns `true` when `v` is a function. - `v` (`any`): Value to validate. -**Return**: +**Returns**: - `isFunction` (`boolean`): Whether the check succeeds. @@ -315,9 +311,9 @@ Returns `true` when `v` is a function. is.Function(function() end) ``` - +--- -#### `nil(v)` +#### `nil(v)` {#nil} Returns `true` when `v` is `nil`. @@ -325,7 +321,7 @@ Returns `true` when `v` is `nil`. - `v` (`any`): Value to validate. -**Return**: +**Returns**: - `isNil` (`boolean`): Whether the check succeeds. @@ -335,9 +331,9 @@ Returns `true` when `v` is `nil`. is.Nil(nil) ``` - +--- -#### `number(v)` +#### `number(v)` {#number} Returns `true` when `v` is a number. @@ -345,7 +341,7 @@ Returns `true` when `v` is a number. - `v` (`any`): Value to validate. -**Return**: +**Returns**: - `isNumber` (`boolean`): Whether the check succeeds. @@ -355,9 +351,9 @@ Returns `true` when `v` is a number. is.number(3.14) ``` - +--- -#### `string(v)` +#### `string(v)` {#string} Returns `true` when `v` is a string. @@ -365,7 +361,7 @@ Returns `true` when `v` is a string. - `v` (`any`): Value to validate. -**Return**: +**Returns**: - `isString` (`boolean`): Whether the check succeeds. @@ -375,9 +371,9 @@ Returns `true` when `v` is a string. is.string("hello") ``` - +--- -#### `table(v)` +#### `table(v)` {#table} Returns `true` when `v` is a table. @@ -385,7 +381,7 @@ Returns `true` when `v` is a table. - `v` (`any`): Value to validate. -**Return**: +**Returns**: - `isTable` (`boolean`): Whether the check succeeds. @@ -395,9 +391,9 @@ Returns `true` when `v` is a table. is.table({}) ``` - +--- -#### `thread(v)` +#### `thread(v)` {#thread} Returns `true` when `v` is a thread. @@ -405,7 +401,7 @@ Returns `true` when `v` is a thread. - `v` (`any`): Value to validate. -**Return**: +**Returns**: - `isThread` (`boolean`): Whether the check succeeds. @@ -415,9 +411,9 @@ Returns `true` when `v` is a thread. is.thread(coroutine.create(function() end)) ``` - +--- -#### `userdata(v)` +#### `userdata(v)` {#userdata} Returns `true` when `v` is userdata. @@ -425,7 +421,7 @@ Returns `true` when `v` is userdata. - `v` (`any`): Value to validate. -**Return**: +**Returns**: - `isUserdata` (`boolean`): Whether the check succeeds. @@ -435,11 +431,11 @@ Returns `true` when `v` is userdata. is.userdata(io.stdout) ``` -### Value Checks +--- - +### Value Checks -#### `callable(v)` +#### `callable(v)` {#callable} Returns `true` when `v` is callable. @@ -447,7 +443,7 @@ Returns `true` when `v` is callable. - `v` (`any`): Value to validate. -**Return**: +**Returns**: - `isCallable` (`boolean`): Whether the check succeeds. @@ -457,9 +453,9 @@ Returns `true` when `v` is callable. is.callable(function() end) ``` - +--- -#### `false(v)` +#### `false(v)` {#false} Returns `true` when `v` is exactly `false`. @@ -467,7 +463,7 @@ Returns `true` when `v` is exactly `false`. - `v` (`any`): Value to validate. -**Return**: +**Returns**: - `isFalse` (`boolean`): Whether the check succeeds. @@ -477,9 +473,9 @@ Returns `true` when `v` is exactly `false`. is.False(false) ``` - +--- -#### `falsy(v)` +#### `falsy(v)` {#falsy} Returns `true` when `v` is falsy. @@ -487,7 +483,7 @@ Returns `true` when `v` is falsy. - `v` (`any`): Value to validate. -**Return**: +**Returns**: - `isFalsy` (`boolean`): Whether the check succeeds. @@ -497,9 +493,9 @@ Returns `true` when `v` is falsy. is.falsy(false) ``` - +--- -#### `integer(v)` +#### `integer(v)` {#integer} Returns `true` when `v` is an integer. @@ -507,7 +503,7 @@ Returns `true` when `v` is an integer. - `v` (`any`): Value to validate. -**Return**: +**Returns**: - `isInteger` (`boolean`): Whether the check succeeds. @@ -517,9 +513,9 @@ Returns `true` when `v` is an integer. is.integer(42) ``` - +--- -#### `true(v)` +#### `true(v)` {#true} Returns `true` when `v` is exactly `true`. @@ -527,7 +523,7 @@ Returns `true` when `v` is exactly `true`. - `v` (`any`): Value to validate. -**Return**: +**Returns**: - `isTrue` (`boolean`): Whether the check succeeds. @@ -537,9 +533,9 @@ Returns `true` when `v` is exactly `true`. is.True(true) ``` - +--- -#### `truthy(v)` +#### `truthy(v)` {#truthy} Returns `true` when `v` is truthy. @@ -547,7 +543,7 @@ Returns `true` when `v` is truthy. - `v` (`any`): Value to validate. -**Return**: +**Returns**: - `isTruthy` (`boolean`): Whether the check succeeds. @@ -556,3 +552,30 @@ Returns `true` when `v` is truthy. ```lua is.truthy("non-empty") ``` + + +[`block(v)`]: #block +[`boolean(v)`]: #boolean +[`callable(v)`]: #callable +[`char(v)`]: #char +[`device(v)`]: #device +[`dir(v)`]: #dir +[`false(v)`]: #false +[`falsy(v)`]: #falsy +[`fifo(v)`]: #fifo +[`file(v)`]: #file +[`function(v)`]: #function +[`integer(v)`]: #integer +[`lfs`]: https://github.com/lunarmodules/luafilesystem +[`link(v)`]: #link +[`nil(v)`]: #nil +[`number(v)`]: #number +[`path(v)`]: #path +[`socket(v)`]: #socket +[`string(v)`]: #string +[`table(v)`]: #table +[`thread(v)`]: #thread +[`true(v)`]: #true +[`truthy(v)`]: #truthy +[`userdata(v)`]: #userdata + diff --git a/docs/api/json.md b/docs/api/json.md index f123b42..7152ce2 100644 --- a/docs/api/json.md +++ b/docs/api/json.md @@ -1,20 +1,18 @@ --- +title: "json" description: "JSON encoding and decoding helpers." --- -# `json` - JSON encoding and decoding helpers. > [!NOTE] > -> This module aims to implement strict -> [RFC 8259](https://www.rfc-editor.org/rfc/rfc8259) JSON behavior. +> This module aims to implement strict [RFC 8259] JSON behavior. ## Usage ```lua -local json = require "mods.json" +local json = mods.json local encoded = json.encode({ ok = true, value = 42 }) local decoded = json.decode(encoded) @@ -103,9 +101,7 @@ assert(json.decode('["\\x"]')) ## Functions - - -### `decode(s)` +### `decode(s)` {#decode} Decode a JSON string into Lua values. @@ -113,10 +109,10 @@ Decode a JSON string into Lua values. - `s` (`string`): JSON string. -**Return**: +**Returns**: - `value` (`any`): Decoded Lua value. -- `err` (`string?`): Error message when decoding fails. +- `err?` (`string`): Error message when decoding fails. **Example**: @@ -127,9 +123,9 @@ print(value.active) --> true print(value.note == json.null) --> true ``` - +--- -### `encode(value, opts?)` +### `encode(value, opts?)` {#encode} Encode a Lua value as JSON. @@ -138,10 +134,10 @@ Encode a Lua value as JSON. - `value` (`any`): Lua value to encode. - `opts?` (`{sort_keys?:boolean, indent?:string}`): Encoding options. -**Return**: +**Returns**: -- `json` (`string?`): JSON string. -- `err` (`string?`): Error message when encoding fails. +- `json?` (`string`): JSON string. +- `err?` (`string`): Error message when encoding fails. **Example**: @@ -163,3 +159,7 @@ print(s) -- ] -- } ``` + + +[RFC 8259]: https://www.rfc-editor.org/rfc/rfc8259 + diff --git a/docs/api/keyword.md b/docs/api/keyword.md index 738d8c4..5d42f2a 100644 --- a/docs/api/keyword.md +++ b/docs/api/keyword.md @@ -1,15 +1,14 @@ --- +title: "keyword" description: "Helpers for Lua keywords and identifiers." --- -# `keyword` - Helpers for Lua keywords and identifiers. ## Usage ```lua -kw = require "mods.keyword" +kw = mods.keyword kw.iskeyword("local")) --> true kw.isidentifier("hello_world") --> true @@ -19,35 +18,33 @@ kw.isidentifier("hello_world") --> true **Collections**: -| Function | Description | -| ------------------------ | ------------------------------------- | -| [`kwlist()`](#fn-kwlist) | Return Lua keywords as a `mods.List`. | -| [`kwset()`](#fn-kwset) | Return Lua keywords as a `mods.Set`. | +| Function | Description | +| ------------ | --------------------------------------- | +| [`kwlist()`] | Return Lua keywords as a [`mods.List`]. | +| [`kwset()`] | Return Lua keywords as a [`mods.Set`]. | **Normalization**: -| Function | Description | -| ----------------------------------------------------- | ---------------------------------------------- | -| [`normalize_identifier(s)`](#fn-normalize-identifier) | Normalize an input into a safe Lua identifier. | +| Function | Description | +| --------------------------- | ---------------------------------------------- | +| [`normalize_identifier(s)`] | Normalize an input into a safe Lua identifier. | **Predicates**: -| Function | Description | -| ------------------------------------- | ------------------------------------------------------------- | -| [`isidentifier(v)`](#fn-isidentifier) | Return `true` when `v` is a valid non-keyword Lua identifier. | -| [`iskeyword(v)`](#fn-iskeyword) | Return `true` when `v` is a reserved Lua keyword. | +| Function | Description | +| ------------------- | ------------------------------------------------------------- | +| [`isidentifier(v)`] | Return `true` when `v` is a valid non-keyword Lua identifier. | +| [`iskeyword(v)`] | Return `true` when `v` is a reserved Lua keyword. | ### Collections - - -#### `kwlist()` +#### `kwlist()` {#kwlist} -Return Lua keywords as a `mods.List`. +Return Lua keywords as a [`mods.List`]. -**Return**: +**Returns**: -- `words` (`mods.List`): List of Lua keywords. +- `words` ([`mods.List`]``): List of Lua keywords. **Example**: @@ -56,15 +53,15 @@ kw.kwlist():contains("and") --> true kw.kwlist():contains("global") --> true -- Lua 5.5+ ``` - +--- -#### `kwset()` +#### `kwset()` {#kwset} -Return Lua keywords as a `mods.Set`. +Return Lua keywords as a [`mods.Set`]. -**Return**: +**Returns**: -- `words` (`mods.Set`): Set of Lua keywords. +- `words` ([`mods.Set`]``): Set of Lua keywords. **Example**: @@ -73,11 +70,11 @@ kw.kwlset():contains("and") --> true kw.kwlset():contains("global") --> true -- Lua 5.5+ ``` -### Normalization +--- - +### Normalization -#### `normalize_identifier(s)` +#### `normalize_identifier(s)` {#normalize-identifier} Normalize an input into a safe Lua identifier. @@ -85,7 +82,7 @@ Normalize an input into a safe Lua identifier. - `s` (`string`): Input string. -**Return**: +**Returns**: - `identifier` (`string`): Normalized Lua identifier. @@ -95,11 +92,11 @@ Normalize an input into a safe Lua identifier. kw.normalize_identifier(" 2 bad-name ") --> "_2_bad_name" ``` -### Predicates +--- - +### Predicates -#### `isidentifier(v)` +#### `isidentifier(v)` {#isidentifier} Return `true` when `v` is a valid non-keyword Lua identifier. @@ -107,7 +104,7 @@ Return `true` when `v` is a valid non-keyword Lua identifier. - `v` (`any`): Value to validate. -**Return**: +**Returns**: - `isIdentifier` (`boolean`): Whether the check succeeds. @@ -118,9 +115,9 @@ kw.isidentifier("hello_world") --> true kw.isidentifier("local") --> false ``` - +--- -#### `iskeyword(v)` +#### `iskeyword(v)` {#iskeyword} Return `true` when `v` is a reserved Lua keyword. @@ -128,7 +125,7 @@ Return `true` when `v` is a reserved Lua keyword. - `v` (`any`): Value to validate. -**Return**: +**Returns**: - `isKeyword` (`boolean`): Whether the check succeeds. @@ -138,3 +135,13 @@ Return `true` when `v` is a reserved Lua keyword. kw.iskeyword("function") --> true kw.iskeyword("hello") --> false ``` + + +[`isidentifier(v)`]: #isidentifier +[`iskeyword(v)`]: #iskeyword +[`kwlist()`]: #kwlist +[`kwset()`]: #kwset +[`mods.List`]: /mods/api/list +[`mods.Set`]: /mods/api/set +[`normalize_identifier(s)`]: #normalize-identifier + diff --git a/docs/api/list.md b/docs/api/list.md index 7a6bba1..2dd7074 100644 --- a/docs/api/list.md +++ b/docs/api/list.md @@ -1,16 +1,15 @@ --- +title: "List" description: "A list class for creating, transforming, and querying sequences of values." --- -# `List` - A list class for creating, transforming, and querying sequences of values. ## Usage ```lua -List = require "mods.List" +List = mods.list ls = List({ "a" }):append("b") print(ls:contains("b")) --> true @@ -27,103 +26,101 @@ print(ls:index("b")) --> 2 **Access**: -| Function | Description | -| ---------------------- | ------------------------------------------- | -| [`first()`](#fn-first) | Return the first element or `nil` if empty. | -| [`last()`](#fn-last) | Return the last element or `nil` if empty. | +| Function | Description | +| ----------- | ------------------------------------------- | +| [`first()`] | Return the first element or `nil` if empty. | +| [`last()`] | Return the last element or `nil` if empty. | **Copies**: -| Function | Description | -| -------------------- | ---------------------------------- | -| [`copy()`](#fn-copy) | Return a shallow copy of the list. | +| Function | Description | +| ---------- | ---------------------------------- | +| [`copy()`] | Return a shallow copy of the list. | **Mutation**: -| Function | Description | -| ------------------------------ | -------------------------------------------------------------------- | -| [`append()`](#fn-append) | Append a value to the end of the list. | -| [`clear()`](#fn-clear) | Remove all elements from the list. | -| [`extend(t)`](#fn-extend) | Extend the list with another list or set. | -| [`extract(pred)`](#fn-extract) | Extract values matching the predicate and remove them from the list. | -| [`insert(pos, v)`](#fn-insert) | Insert a value at the given position. | -| [`insert(v)`](#fn-insert) | Append a value to the end of the list. | -| [`pop()`](#fn-pop) | Remove and return the last element. | -| [`pop(pos)`](#fn-pop) | Remove and return the element at the given position. | -| [`prepend(v)`](#fn-prepend) | Insert a value at the start of the list. | -| [`remove(v)`](#fn-remove) | Remove the first matching value. | -| [`shuffle(rng?)`](#fn-shuffle) | Shuffle the list in place. | -| [`sort(comp?)`](#fn-sort) | Sort the list in place. | +| Function | Description | +| ------------------ | -------------------------------------------------------------------- | +| [`append()`] | Append a value to the end of the list. | +| [`clear()`] | Remove all elements from the list. | +| [`extend(t)`] | Extend the list with another list or set. | +| [`extract(pred)`] | Extract values matching the predicate and remove them from the list. | +| [`insert(pos, v)`] | Insert a value at the given position. | +| [`insert(v)`] | Append a value to the end of the list. | +| [`pop()`] | Remove and return the last element. | +| [`pop(pos)`] | Remove and return the element at the given position. | +| [`prepend(v)`] | Insert a value at the start of the list. | +| [`remove(v)`] | Remove the first matching value. | +| [`shuffle(rng?)`] | Shuffle the list in place. | +| [`sort(comp?)`] | Sort the list in place. | **Predicates**: -| Function | Description | -| -------------------------- | ------------------------------------------------- | -| [`all(pred)`](#fn-all) | Return `true` if all values match the predicate. | -| [`any(pred)`](#fn-any) | Return `true` if any value matches the predicate. | -| [`equals(ls)`](#fn-equals) | Compare two lists using shallow element equality. | -| [`le(ls)`](#fn-le) | Compare two lists lexicographically. | -| [`lt(ls)`](#fn-lt) | Compare two lists lexicographically. | +| Function | Description | +| -------------- | ------------------------------------------------- | +| [`all(pred)`] | Return `true` if all values match the predicate. | +| [`any(pred)`] | Return `true` if any value matches the predicate. | +| [`equals(ls)`] | Compare two lists using shallow element equality. | +| [`le(ls)`] | Compare two lists lexicographically. | +| [`lt(ls)`] | Compare two lists lexicographically. | **Queries**: -| Function | Description | -| -------------------------------- | ----------------------------------------------------------- | -| [`contains(v)`](#fn-contains) | Return `true` if the list contains the value. | -| [`count(v)`](#fn-count) | Count how many times a value appears. | -| [`index(v)`](#fn-index) | Return the index of the first matching value. | -| [`index_if(pred)`](#fn-index-if) | Return the index of the first value matching the predicate. | -| [`isempty()`](#fn-isempty) | Return whether the list has no elements. | -| [`len()`](#fn-len) | Return the number of elements in the list. | +| Function | Description | +| ------------------ | ----------------------------------------------------------- | +| [`contains(v)`] | Return `true` if the list contains the value. | +| [`count(v)`] | Count how many times a value appears. | +| [`index(v)`] | Return the index of the first matching value. | +| [`index_if(pred)`] | Return the index of the first value matching the predicate. | +| [`isempty()`] | Return whether the list has no elements. | +| [`len()`] | Return the number of elements in the list. | **Transforms**: -| Function | Description | -| ------------------------------------- | -------------------------------------------------------------------- | -| [`concat(sep?, i?, j?)`](#fn-concat) | Concatenate list values using Lua's native `table.concat` behavior. | -| [`difference(t)`](#fn-difference) | Return a new list with values not in the given list or set. | -| [`drop(n)`](#fn-drop) | Return a new list without the first n elements. | -| [`filter(pred)`](#fn-filter) | Return a new list with values matching the predicate. | -| [`flatten()`](#fn-flatten) | Flatten one level of nested lists. | -| [`foreach(fn)`](#fn-foreach) | Apply a function to each element (for side effects). | -| [`group_by(fn)`](#fn-group-by) | Group list values by a computed key. | -| [`intersection(t)`](#fn-intersection) | Return values that are also present in the given list or set. | -| [`invert()`](#fn-invert) | Invert values to indices in a new table. | -| [`join(sep?, quoted?)`](#fn-join) | Join list values into a string. | -| [`keypath()`](#fn-keypath) | Render list items as a table-access key path. | -| [`map(fn)`](#fn-map) | Return a new list by mapping each value. | -| [`mirror()`](#fn-mirror) | Mirror values into a new table as both keys and values. | -| [`mul(n)`](#fn-mul) | Return a new list repeated `n` times (list multiplication behavior). | -| [`reduce(fn, init?)`](#fn-reduce) | Reduce the list to a single value using an accumulator. | -| [`reverse()`](#fn-reverse) | Reverse the list in place. | -| [`slice(i?, j?)`](#fn-slice) | Return a new list containing items from i to j (inclusive). | -| [`take(n)`](#fn-take) | Return the first n elements as a new list. | -| [`toset()`](#fn-toset) | Convert the list to a set. | -| [`tostring()`](#fn-tostring) | Render the list to a string via the regular method form. | -| [`uniq()`](#fn-uniq) | Return a new list with duplicates removed (first occurrence kept). | -| [`zip(t)`](#fn-zip) | Zip two collections into a list of 2-element tables. | +| Function | Description | +| ------------------------ | -------------------------------------------------------------------- | +| [`concat(sep?, i?, j?)`] | Concatenate list values using Lua's native `table.concat` behavior. | +| [`difference(t)`] | Return a new list with values not in the given list or set. | +| [`drop(n)`] | Return a new list without the first n elements. | +| [`filter(pred)`] | Return a new list with values matching the predicate. | +| [`flatten()`] | Flatten one level of nested lists. | +| [`foreach(fn)`] | Apply a function to each element (for side effects). | +| [`group_by(fn)`] | Group list values by a computed key. | +| [`intersection(t)`] | Return values that are also present in the given list or set. | +| [`invert()`] | Invert values to indices in a new table. | +| [`join(sep?, quoted?)`] | Join list values into a string. | +| [`keypath()`] | Render list items as a table-access key path. | +| [`map(fn)`] | Return a new list by mapping each value. | +| [`mirror()`] | Mirror values into a new table as both keys and values. | +| [`mul(n)`] | Return a new list repeated `n` times (list multiplication behavior). | +| [`reduce(fn, init?)`] | Reduce the list to a single value using an accumulator. | +| [`reverse()`] | Reverse the list in place. | +| [`slice(i?, j?)`] | Return a new list containing items from i to j (inclusive). | +| [`take(n)`] | Return the first n elements as a new list. | +| [`toset()`] | Convert the list to a set. | +| [`tostring()`] | Render the list to a string via the regular method form. | +| [`uniq()`] | Return a new list with duplicates removed (first occurrence kept). | +| [`zip(t)`] | Zip two collections into a list of 2-element tables. | **Metamethods**: -| Function | Description | -| ------------------------------ | --------------------------------------------------------------------------------------------------------------- | -| [`__add(ls)`](#fn-add) | Extend the left-hand list in place with right-hand values, then return the same left-hand list reference (`+`). | -| [`__eq(ls)`](#fn-eq) | Compare two lists using shallow element equality (`==`). | -| [`__le(ls)`](#fn-le) | Compare two lists lexicographically (`<=`). | -| [`__lt(ls)`](#fn-lt) | Compare two lists lexicographically (`<`). | -| [`__mul(n)`](#fn-mul) | Repeat a list `n` times (`*`). | -| [`__sub(ls)`](#fn-sub) | Return values from the left list that are not present in the right list (`-`). | -| [`__tostring()`](#fn-tostring) | Render the list to a string like `{ "a", "b", 1 }`. | +| Function | Description | +| ---------------- | --------------------------------------------------------------------------------------------------------------- | +| [`__add(ls)`] | Extend the left-hand list in place with right-hand values, then return the same left-hand list reference (`+`). | +| [`__eq(ls)`] | Compare two lists using shallow element equality (`==`). | +| [`__le(ls)`] | Compare two lists lexicographically (`<=`). | +| [`__lt(ls)`] | Compare two lists lexicographically (`<`). | +| [`__mul(n)`] | Repeat a list `n` times (`*`). | +| [`__sub(ls)`] | Return values from the left list that are not present in the right list (`-`). | +| [`__tostring()`] | Render the list to a string like `{ "a", "b", 1 }`. | ### Access - - -#### `first()` +#### `first()` {#first} Return the first element or `nil` if empty. -**Return**: +**Returns**: - `firstValue` (`any`): First value, or `nil` if empty. @@ -133,13 +130,13 @@ Return the first element or `nil` if empty. v = List({ "a", "b" }):first() --> "a" ``` - +--- -#### `last()` +#### `last()` {#last} Return the last element or `nil` if empty. -**Return**: +**Returns**: - `lastValue` (`any`): Last value, or `nil` if empty. @@ -149,17 +146,17 @@ Return the last element or `nil` if empty. v = List({ "a", "b" }):last() --> "b" ``` -### Copies +--- - +### Copies -#### `copy()` +#### `copy()` {#copy} Return a shallow copy of the list. -**Return**: +**Returns**: -- `ls` (`mods.List`): New list. +- `ls` ([`mods.List`]): New list. **Example**: @@ -167,15 +164,15 @@ Return a shallow copy of the list. c = List({ "a", "b" }):copy() --> { "a", "b" } ``` -### Mutation +--- - +### Mutation -#### `append()` +#### `append()` {#append} Append a value to the end of the list. -**Return**: +**Returns**: - `self` (`T`): Current list. @@ -185,13 +182,13 @@ Append a value to the end of the list. ls = List({ "a" }):append("b") --> { "a", "b" } ``` - +--- -#### `clear()` +#### `clear()` {#clear} Remove all elements from the list. -**Return**: +**Returns**: - `self` (`T`): Current list. @@ -201,17 +198,17 @@ Remove all elements from the list. ls = List({ "a", "b" }):clear() --> { } ``` - +--- -#### `extend(t)` +#### `extend(t)` {#extend} Extend the list with another list or set. **Parameters**: -- `t` (`mods.List|mods.Set|any[]`): Values to append. +- `t` ([`mods.List`] | [`mods.Set`] | `any[]`): Values to append. -**Return**: +**Returns**: - `self` (`T`): Current list. @@ -226,9 +223,9 @@ ls = List({ "a" }):extend(Set({ "b", "c" })) --> { "a", "b", "c" } > > `extend` is also available through the `+` operator. - +--- -#### `extract(pred)` +#### `extract(pred)` {#extract} Extract values matching the predicate and remove them from the list. @@ -236,9 +233,9 @@ Extract values matching the predicate and remove them from the list. - `pred` (`fun(v:any):boolean`): Predicate function. -**Return**: +**Returns**: -- `ls` (`mods.List`): Extracted values. +- `ls` ([`mods.List`]): Extracted values. **Example**: @@ -248,9 +245,9 @@ is_len_1 = function(v) return #v == 1 end ex = ls:extract(is_len_1) --> ex = { "a", "c" }, ls = { "bb" } ``` - +--- -#### `insert(pos, v)` +#### `insert(pos, v)` {#insert} Insert a value at the given position. @@ -259,7 +256,7 @@ Insert a value at the given position. - `pos` (`integer`): Insert position. - `v` (`any`): Value to insert. -**Return**: +**Returns**: - `self` (`T`): Current list. @@ -269,9 +266,9 @@ Insert a value at the given position. ls = List({ "a", "c" }):insert(2, "b") --> { "a", "b", "c" } ``` - +--- -#### `insert(v)` +#### `insert(v)` {#insert-1} Append a value to the end of the list. @@ -279,7 +276,7 @@ Append a value to the end of the list. - `v` (`any`): Value to append. -**Return**: +**Returns**: - `self` (`T`): Current list. @@ -289,13 +286,13 @@ Append a value to the end of the list. ls = List({ "a", "b" }):insert("c") --> { "a", "b", "c" } ``` - +--- -#### `pop()` +#### `pop()` {#pop} Remove and return the last element. -**Return**: +**Returns**: - `removedValue` (`any`): Removed value. @@ -306,9 +303,9 @@ ls = List({ "a", "b" }) v = ls:pop() --> v == "b"; ls is { "a" } ``` - +--- -#### `pop(pos)` +#### `pop(pos)` {#pop-1} Remove and return the element at the given position. @@ -316,7 +313,7 @@ Remove and return the element at the given position. - `pos` (`integer`): Numeric value. -**Return**: +**Returns**: - `removedValue` (`any`): Removed value. @@ -327,9 +324,9 @@ ls = List({ "a", "b", "c" }) v = ls:pop(2) --> v == "b"; ls is { "a", "c" } ``` - +--- -#### `prepend(v)` +#### `prepend(v)` {#prepend} Insert a value at the start of the list. @@ -337,7 +334,7 @@ Insert a value at the start of the list. - `v` (`any`): Value to validate. -**Return**: +**Returns**: - `self` (`T`): Current list. @@ -348,9 +345,9 @@ ls = List({ "b", "c" }) ls:prepend("a") --> { "a", "b", "c" } ``` - +--- -#### `remove(v)` +#### `remove(v)` {#remove} Remove the first matching value. @@ -358,7 +355,7 @@ Remove the first matching value. - `v` (`any`): Value to validate. -**Return**: +**Returns**: - `self` (`T`): Current list. @@ -369,9 +366,9 @@ ls = List({ "a", "b", "b" }) ls:remove("b") --> { "a", "b" } ``` - +--- -#### `shuffle(rng?)` +#### `shuffle(rng?)` {#shuffle} Shuffle the list in place. @@ -380,7 +377,7 @@ Shuffle the list in place. - `rng?` (`fun(lo:integer, hi:integer):integer`): Optional random index picker; defaults to `math.random`. -**Return**: +**Returns**: - `self` (`T`): Current list. @@ -390,9 +387,9 @@ Shuffle the list in place. ls = List({ "a", "b", "c" }):shuffle() --> { "b", "c", "a" } -- order varies ``` - +--- -#### `sort(comp?)` +#### `sort(comp?)` {#sort} Sort the list in place. @@ -401,7 +398,7 @@ Sort the list in place. - `comp?` (`fun(a:any, b:any):boolean`): Optional comparison function (defaults to `nil`). -**Return**: +**Returns**: - `self` (`T`): Current list. @@ -417,11 +414,11 @@ words:sort(function(a, b) end) --> { "a", "bb", "ccc" } ``` -### Predicates +--- - +### Predicates -#### `all(pred)` +#### `all(pred)` {#all} Return `true` if all values match the predicate. @@ -429,7 +426,7 @@ Return `true` if all values match the predicate. - `pred` (`fun(v:any):boolean`): Predicate function. -**Return**: +**Returns**: - `allMatch` (`boolean`): Whether the condition is met. @@ -444,9 +441,9 @@ ok = List({ 2, 4 }):all(is_even) --> true > > Empty lists return `true`. - +--- -#### `any(pred)` +#### `any(pred)` {#any} Return `true` if any value matches the predicate. @@ -454,7 +451,7 @@ Return `true` if any value matches the predicate. - `pred` (`fun(v:any):boolean`): Predicate function. -**Return**: +**Returns**: - `anyMatch` (`boolean`): Whether the condition is met. @@ -465,17 +462,17 @@ has_len_2 = function(v) return #v == 2 end ok = List({ "a", "bb" }):any(has_len_2) --> true ``` - +--- -#### `equals(ls)` +#### `equals(ls)` {#equals} Compare two lists using shallow element equality. **Parameters**: -- `ls` (`mods.List|any[]`): Other list value. +- `ls` ([`mods.List`] | `any[]`): Other list value. -**Return**: +**Returns**: - `isEqual` (`boolean`): Whether the condition is met. @@ -516,17 +513,17 @@ ok = a:equals(b) --> true > ok = a:equals(b) --> true > ``` - +--- -#### `le(ls)` +#### `le(ls)` {#le} Compare two lists lexicographically. **Parameters**: -- `ls` (`mods.List|any[]`): Other list value. +- `ls` ([`mods.List`] | `any[]`): Other list value. -**Return**: +**Returns**: - `isLessOrEqual` (`boolean`): Whether the condition is met. @@ -541,17 +538,17 @@ ok = List({ 1, 2 }):le({ 1, 1 }) --> false > > `le` is also available through the `<=` operator. - +--- -#### `lt(ls)` +#### `lt(ls)` {#lt} Compare two lists lexicographically. **Parameters**: -- `ls` (`mods.List|any[]`): Other list value. +- `ls` ([`mods.List`] | `any[]`): Other list value. -**Return**: +**Returns**: - `isLess` (`boolean`): Whether the condition is met. @@ -566,11 +563,11 @@ ok = List({ 1, 2 }):lt({ 1, 2, 0 }) --> true > > `lt` is also available through the `<` operator. -### Queries +--- - +### Queries -#### `contains(v)` +#### `contains(v)` {#contains} Return `true` if the list contains the value. @@ -578,7 +575,7 @@ Return `true` if the list contains the value. - `v` (`any`): Value to validate. -**Return**: +**Returns**: - `isPresent` (`boolean`): True when `v` is present in the list. @@ -588,9 +585,9 @@ Return `true` if the list contains the value. ok = List({ "a", "b" }):contains("b") --> true ``` - +--- -#### `count(v)` +#### `count(v)` {#count} Count how many times a value appears. @@ -598,7 +595,7 @@ Count how many times a value appears. - `v` (`any`): Value to validate. -**Return**: +**Returns**: - `res` (`integer`): Result count. @@ -608,9 +605,9 @@ Count how many times a value appears. n = List({ "a", "b", "b" }):count("b") --> 2 ``` - +--- -#### `index(v)` +#### `index(v)` {#index} Return the index of the first matching value. @@ -618,9 +615,9 @@ Return the index of the first matching value. - `v` (`any`): Value to validate. -**Return**: +**Returns**: -- `index` (`integer?`): Result index, or nil when not found. +- `index?` (`integer`): Result index, or nil when not found. **Example**: @@ -628,9 +625,9 @@ Return the index of the first matching value. i = List({ "a", "b", "c", "b" }):index("b") --> 2 ``` - +--- -#### `index_if(pred)` +#### `index_if(pred)` {#index-if} Return the index of the first value matching the predicate. @@ -638,9 +635,9 @@ Return the index of the first value matching the predicate. - `pred` (`fun(v:any):boolean`): Predicate function. -**Return**: +**Returns**: -- `index` (`integer?`): Result index, or nil when no value matches. +- `index?` (`integer`): Result index, or nil when no value matches. **Example**: @@ -649,13 +646,13 @@ gt_1 = function(x) return x > 1 end i = List({ 1, 2, 3 }):index_if(gt_1) --> 2 ``` - +--- -#### `isempty()` +#### `isempty()` {#isempty} Return whether the list has no elements. -**Return**: +**Returns**: - `empty` (`boolean`): `true` when the list has no elements. @@ -665,13 +662,13 @@ Return whether the list has no elements. ok = List():isempty() --> true ``` - +--- -#### `len()` +#### `len()` {#len} Return the number of elements in the list. -**Return**: +**Returns**: - `count` (`integer`): Element count. @@ -685,11 +682,11 @@ n = List({ "a", "b", "c" }):len() --> 3 > > Uses Lua's `#` operator. -### Transforms +--- - +### Transforms -#### `concat(sep?, i?, j?)` +#### `concat(sep?, i?, j?)` {#concat} Concatenate list values using Lua's native `table.concat` behavior. @@ -699,7 +696,7 @@ Concatenate list values using Lua's native `table.concat` behavior. - `i?` (`integer`): Optional start index (defaults to `1`). - `j?` (`integer`): Optional end index (defaults to `#self`). -**Return**: +**Returns**: - `concatenated` (`string`): Concatenated string. @@ -714,17 +711,17 @@ s = List({ "a", "b", "c" }):concat(",") --> "a,b,c" > This method forwards to `table.concat` directly and keeps its strict element > rules. - +--- -#### `difference(t)` +#### `difference(t)` {#difference} Return a new list with values not in the given list or set. **Parameters**: -- `t` (`mods.List|mods.Set|any[]`): Values to remove. +- `t` ([`mods.List`] | [`mods.Set`] | `any[]`): Values to remove. -**Return**: +**Returns**: - `ls` (`T`): New list. @@ -738,9 +735,9 @@ d = List({ "a", "b", "c" }):difference({ "b" }) --> { "a", "c" } > > `difference` is also available through the `-` operator. - +--- -#### `drop(n)` +#### `drop(n)` {#drop} Return a new list without the first n elements. @@ -748,9 +745,9 @@ Return a new list without the first n elements. - `n` (`integer`): Numeric value. -**Return**: +**Returns**: -- `ls` (`mods.List`): New list. +- `ls` ([`mods.List`]): New list. **Example**: @@ -758,9 +755,9 @@ Return a new list without the first n elements. t = List({ "a", "b", "c" }):drop(1) --> { "b", "c" } ``` - +--- -#### `filter(pred)` +#### `filter(pred)` {#filter} Return a new list with values matching the predicate. @@ -768,9 +765,9 @@ Return a new list with values matching the predicate. - `pred` (`fun(v:any):boolean`): Predicate function. -**Return**: +**Returns**: -- `ls` (`mods.List`): New list. +- `ls` ([`mods.List`]): New list. **Example**: @@ -779,15 +776,15 @@ is_len_1 = function(v) return #v == 1 end f = List({ "a", "bb", "c" }):filter(is_len_1) --> { "a", "c" } ``` - +--- -#### `flatten()` +#### `flatten()` {#flatten} Flatten one level of nested lists. -**Return**: +**Returns**: -- `ls` (`mods.List`): New list. +- `ls` ([`mods.List`]): New list. **Example**: @@ -795,9 +792,9 @@ Flatten one level of nested lists. f = List({ { "a", "b" }, { "c" } }):flatten() --> { "a", "b", "c" } ``` - +--- -#### `foreach(fn)` +#### `foreach(fn)` {#foreach} Apply a function to each element (for side effects). @@ -805,7 +802,7 @@ Apply a function to each element (for side effects). - `fn` (`fun(v:any)`): Callback function. -**Return**: +**Returns**: - `none` (`nil`) @@ -817,9 +814,9 @@ List({ "a", "b" }):foreach(print) --> prints -> b ``` - +--- -#### `group_by(fn)` +#### `group_by(fn)` {#group-by} Group list values by a computed key. @@ -827,7 +824,7 @@ Group list values by a computed key. - `fn` (`fun(v:any):any`): Callback function. -**Return**: +**Returns**: - `groups` (`table`): Groups keyed by the callback result. @@ -838,19 +835,19 @@ words = { "aa", "b", "ccc", "dd" } g = List(words):group_by(string.len) --> { {"b"}, { "aa", "dd" }, { "ccc" } } ``` - +--- -#### `intersection(t)` +#### `intersection(t)` {#intersection} Return values that are also present in the given list or set. **Parameters**: -- `t` (`mods.List|mods.Set|any[]`): Other list/set. +- `t` ([`mods.List`] | [`mods.Set`] | `any[]`): Other list/set. -**Return**: +**Returns**: -- `ls` (`mods.List`): New list. +- `ls` ([`mods.List`]): New list. **Example**: @@ -863,13 +860,13 @@ i = List({ "a", "b", "a", "c" }):intersection({ "a", "c" }) > > Order is preserved from the original list. - +--- -#### `invert()` +#### `invert()` {#invert} Invert values to indices in a new table. -**Return**: +**Returns**: - `idxByValue` (`table`): Table mapping each value to its last index. @@ -879,9 +876,9 @@ Invert values to indices in a new table. t = List({ "a", "b", "c" }):invert() --> { a = 1, b = 2, c = 3 } ``` - +--- -#### `join(sep?, quoted?)` +#### `join(sep?, quoted?)` {#join} Join list values into a string. @@ -890,7 +887,7 @@ Join list values into a string. - `sep?` (`string`): Optional separator value (defaults to `""`). - `quoted?` (`boolean`): Optional boolean flag (defaults to `false`). -**Return**: +**Returns**: - `joined` (`string`): Joined string. @@ -906,13 +903,13 @@ s = List({ "a", "b", "c" }):join(", ", true) --> '"a", "b", "c"' > Values are converted with `tostring` before joining. Set `quoted = true` to > quote string values. - +--- -#### `keypath()` +#### `keypath()` {#keypath} Render list items as a table-access key path. -**Return**: +**Returns**: - `keyPath` (`string`): Key-path string. @@ -922,9 +919,9 @@ Render list items as a table-access key path. p = List({ "ctx", "users", 1, "name" }):keypath() --> "ctx.users[1].name" ``` - +--- -#### `map(fn)` +#### `map(fn)` {#map} Return a new list by mapping each value. @@ -932,9 +929,9 @@ Return a new list by mapping each value. - `fn` (`fun(value:T):any`): Callback function. -**Return**: +**Returns**: -- `ls` (`mods.List`): New list. +- `ls` ([`mods.List`]): New list. **Example**: @@ -943,13 +940,13 @@ to_upper = function(v) return v:upper() end m = List({ "a", "b" }):map(to_upper) --> { "A", "B" } ``` - +--- -#### `mirror()` +#### `mirror()` {#mirror} Mirror values into a new table as both keys and values. -**Return**: +**Returns**: - `mirroredValues` (`table`): Table mapping each value to itself. @@ -959,9 +956,9 @@ Mirror values into a new table as both keys and values. t = List({ "a", "b", "c" }):mirror() --> { a = "a", b = "b", c = "c" } ``` - +--- -#### `mul(n)` +#### `mul(n)` {#mul} Return a new list repeated `n` times (list multiplication behavior). @@ -969,9 +966,9 @@ Return a new list repeated `n` times (list multiplication behavior). - `n` (`integer`): Numeric value. -**Return**: +**Returns**: -- `ls` (`mods.List`): New list. +- `ls` ([`mods.List`]): New list. **Example**: @@ -983,9 +980,9 @@ ls = List({ "a", "b" }):mul(3) --> { "a", "b", "a", "b", "a", "b" } > > `mul` is also available through the `*` operator. - +--- -#### `reduce(fn, init?)` +#### `reduce(fn, init?)` {#reduce} Reduce the list to a single value using an accumulator. @@ -995,7 +992,7 @@ Reduce the list to a single value using an accumulator. - `init?` (`any`): Optional initial accumulator; for non-empty lists, `nil` or omitted uses the first item. -**Return**: +**Returns**: - `reducedValue` (`any`): Reduced value. @@ -1011,15 +1008,15 @@ sum = List({ 1, 2, 3 }):reduce(add, 10) --> 16 > > For empty lists, returns `init` unchanged (or `nil` when omitted). - +--- -#### `reverse()` +#### `reverse()` {#reverse} Reverse the list in place. -**Return**: +**Returns**: -- `ls` (`mods.List`): Same list, reversed in place. +- `ls` ([`mods.List`]): Same list, reversed in place. **Example**: @@ -1027,9 +1024,9 @@ Reverse the list in place. r = List({ "a", "b", "c" }):reverse() --> { "c", "b", "a" } ``` - +--- -#### `slice(i?, j?)` +#### `slice(i?, j?)` {#slice} Return a new list containing items from i to j (inclusive). @@ -1038,9 +1035,9 @@ Return a new list containing items from i to j (inclusive). - `i?` (`integer`): Optional start index (defaults to `1`). - `j?` (`integer`): Optional end index (defaults to `#self`). -**Return**: +**Returns**: -- `ls` (`mods.List`): New list. +- `ls` ([`mods.List`]): New list. **Example**: @@ -1052,9 +1049,9 @@ t = List({ "a", "b", "c", "d" }):slice(2, 3) --> { "b", "c" } > > Supports negative indices (-1 is last element). - +--- -#### `take(n)` +#### `take(n)` {#take} Return the first n elements as a new list. @@ -1062,9 +1059,9 @@ Return the first n elements as a new list. - `n` (`integer`): Numeric value. -**Return**: +**Returns**: -- `ls` (`mods.List`): New list. +- `ls` ([`mods.List`]): New list. **Example**: @@ -1072,15 +1069,15 @@ Return the first n elements as a new list. t = List({ "a", "b", "c" }):take(2) --> { "a", "b" } ``` - +--- -#### `toset()` +#### `toset()` {#toset} Convert the list to a set. -**Return**: +**Returns**: -- `set` (`mods.Set`): New set. +- `set` ([`mods.Set`]): New set. **Example**: @@ -1092,13 +1089,13 @@ s = List({ "a", "b", "a" }):toset() --> { a = true, b = true } > > Order is preserved from the original list. - +--- -#### `tostring()` +#### `tostring()` {#tostring} Render the list to a string via the regular method form. -**Return**: +**Returns**: - `renderedList` (`string`): Rendered list string. @@ -1108,15 +1105,15 @@ Render the list to a string via the regular method form. s = List({ "a", "b", 1 }):tostring() --> '{ "a", "b", 1 }' ``` - +--- -#### `uniq()` +#### `uniq()` {#uniq} Return a new list with duplicates removed (first occurrence kept). -**Return**: +**Returns**: -- `ls` (`mods.List`): New list. +- `ls` ([`mods.List`]): New list. **Example**: @@ -1124,19 +1121,19 @@ Return a new list with duplicates removed (first occurrence kept). u = List({ "a", "b", "a", "c" }):uniq() --> { "a", "b", "c" } ``` - +--- -#### `zip(t)` +#### `zip(t)` {#zip} Zip two collections into a list of 2-element tables. **Parameters**: -- `t` (`mods.List|mods.Set|any[]`): Values to pair with. +- `t` ([`mods.List`] | [`mods.Set`] | `any[]`): Values to pair with. -**Return**: +**Returns**: -- `ls` (`mods.List`): New list. +- `ls` ([`mods.List`]): New list. **Example**: @@ -1149,22 +1146,22 @@ z = List({ "a", "b" }):zip(Set({ 1, 2 })) --> { {"a",1}, {"b",2} } > > Length is the minimum of both tables' lengths. -### Metamethods +--- - +### Metamethods -#### `__add(ls)` +#### `__add(ls)` {#add} Extend the left-hand list in place with right-hand values, then return the same left-hand list reference (`+`). **Parameters**: -- `ls` (`mods.List|any[]`): Other list value. +- `ls` ([`mods.List`] | `any[]`): Other list value. -**Return**: +**Returns**: -- `self` (`mods.List|any[]`): Current list. +- `self` ([`mods.List`] | `any[]`): Current list. **Example**: @@ -1178,17 +1175,17 @@ c = a + b --> c and a are the same reference: { "a", "b", "c", "d" } > > `+` operator is equivalent to `:extend(ls)`. - +--- -#### `__eq(ls)` +#### `__eq(ls)` {#eq} Compare two lists using shallow element equality (`==`). **Parameters**: -- `ls` (`mods.List|any[]`): Other list value. +- `ls` ([`mods.List`] | `any[]`): Other list value. -**Return**: +**Returns**: - `isEqual` (`boolean`): Whether the condition is met. @@ -1227,17 +1224,17 @@ ok = a == b --> true (same nested table reference) > ok = (a == b) --> true > ``` - +--- -#### `__le(ls)` +#### `__le(ls)` {#le-1} Compare two lists lexicographically (`<=`). **Parameters**: -- `ls` (`mods.List|any[]`): Other list value. +- `ls` ([`mods.List`] | `any[]`): Other list value. -**Return**: +**Returns**: - `isLessOrEqual` (`boolean`): Whether the condition is met. @@ -1251,17 +1248,17 @@ ok = List({ 1, 2 }) <= List({ 1, 2 }) --> true > > `<=` is equivalent to `:le(ls)`. - +--- -#### `__lt(ls)` +#### `__lt(ls)` {#lt-1} Compare two lists lexicographically (`<`). **Parameters**: -- `ls` (`mods.List|any[]`): Other list value. +- `ls` ([`mods.List`] | `any[]`): Other list value. -**Return**: +**Returns**: - `isLess` (`boolean`): Whether the condition is met. @@ -1275,19 +1272,19 @@ ok = List({ 1, 2 }) < List({ 1, 3 }) --> true > > `<` is equivalent to `:lt(ls)`. - +--- -#### `__mul(n)` +#### `__mul(n)` {#mul-1} Repeat a list `n` times (`*`). **Parameters**: -- `n` (`integer|mods.List`): Right operand. +- `n` (`integer` | [`mods.List`]): Right operand. -**Return**: +**Returns**: -- `ls` (`mods.List`): New list. +- `ls` ([`mods.List`]): New list. **Example**: @@ -1300,19 +1297,19 @@ l2 = 3 * List({ "a", "b" }) --> { "a", "b", "a", "b", "a", "b" } > > `*` is equivalent to `:mul(n)`. - +--- -#### `__sub(ls)` +#### `__sub(ls)` {#sub} Return values from the left list that are not present in the right list (`-`). **Parameters**: -- `ls` (`mods.List|any[]`): Other list value. +- `ls` ([`mods.List`] | `any[]`): Other list value. -**Return**: +**Returns**: -- `ls` (`mods.List`): New list. +- `ls` ([`mods.List`]): New list. **Example**: @@ -1326,13 +1323,13 @@ d = a - b --> { "a", "c" } > > `-` operator is equivalent to `:difference(ls)`. - +--- -#### `__tostring()` +#### `__tostring()` {#tostring-1} Render the list to a string like `{ "a", "b", 1 }`. -**Return**: +**Returns**: - `renderedList` (`string`): Rendered list string. @@ -1341,3 +1338,63 @@ Render the list to a string like `{ "a", "b", 1 }`. ```lua s = tostring(List({ "a", "b", 1 })) --> '{ "a", "b", 1 }' ``` + + +[`__add(ls)`]: #add +[`__eq(ls)`]: #eq +[`__le(ls)`]: #le-1 +[`__lt(ls)`]: #lt-1 +[`__mul(n)`]: #mul-1 +[`__sub(ls)`]: #sub +[`__tostring()`]: #tostring-1 +[`all(pred)`]: #all +[`any(pred)`]: #any +[`append()`]: #append +[`clear()`]: #clear +[`concat(sep?, i?, j?)`]: #concat +[`contains(v)`]: #contains +[`copy()`]: #copy +[`count(v)`]: #count +[`difference(t)`]: #difference +[`drop(n)`]: #drop +[`equals(ls)`]: #equals +[`extend(t)`]: #extend +[`extract(pred)`]: #extract +[`filter(pred)`]: #filter +[`first()`]: #first +[`flatten()`]: #flatten +[`foreach(fn)`]: #foreach +[`group_by(fn)`]: #group-by +[`index(v)`]: #index +[`index_if(pred)`]: #index-if +[`insert(pos, v)`]: #insert +[`insert(v)`]: #insert-1 +[`intersection(t)`]: #intersection +[`invert()`]: #invert +[`isempty()`]: #isempty +[`join(sep?, quoted?)`]: #join +[`keypath()`]: #keypath +[`last()`]: #last +[`le(ls)`]: #le +[`len()`]: #len +[`lt(ls)`]: #lt +[`map(fn)`]: #map +[`mirror()`]: #mirror +[`mods.List`]: /mods/api/list +[`mods.Set`]: /mods/api/set +[`mul(n)`]: #mul +[`pop()`]: #pop +[`pop(pos)`]: #pop-1 +[`prepend(v)`]: #prepend +[`reduce(fn, init?)`]: #reduce +[`remove(v)`]: #remove +[`reverse()`]: #reverse +[`shuffle(rng?)`]: #shuffle +[`slice(i?, j?)`]: #slice +[`sort(comp?)`]: #sort +[`take(n)`]: #take +[`toset()`]: #toset +[`tostring()`]: #tostring +[`uniq()`]: #uniq +[`zip(t)`]: #zip + diff --git a/docs/api/log.md b/docs/api/log.md index 749b4f0..1e8160a 100644 --- a/docs/api/log.md +++ b/docs/api/log.md @@ -1,18 +1,17 @@ --- +title: "log" description: "Logger factory that emits normalized records through an optional custom handler." --- -# `log` - Logger factory that emits normalized records through an optional custom handler. When `opts.handler` is omitted, records are written to `io.stderr`. ## Usage ```lua -log = require "mods.log" +log = mods.log local logger = log.new() logger:warn("config missing") --> writes: [WARN]: config missing @@ -22,73 +21,83 @@ logger:warn("config missing") --> writes: [WARN]: config missing **Factory**: -| Function | Description | -| ----------------------- | -------------------- | -| [`new(opts?)`](#fn-new) | Create a new logger. | +| Function | Description | +| -------------- | -------------------- | +| [`new(opts?)`] | Create a new logger. | **Logger Methods**: -| Function | Description | -| -------------------------------- | ----------------------------------------------------------- | -| [`debug(...)`](#fn-debug) | Emit a `debug` record. | -| [`error(...)`](#fn-error) | Emit an `error` record. | -| [`info(...)`](#fn-info) | Emit an `info` record. | -| [`log(levelname, ...)`](#fn-log) | Emit a record for `level` when it passes the logger filter. | -| [`warn(...)`](#fn-warn) | Emit a `warn` record. | +| Function | Description | +| ----------------------- | ----------------------------------------------------------- | +| [`debug(...)`] | Emit a `debug` record. | +| [`error(...)`] | Emit an `error` record. | +| [`info(...)`] | Emit an `info` record. | +| [`log(levelname, ...)`] | Emit a record for `level` when it passes the logger filter. | +| [`warn(...)`] | Emit a `warn` record. | ### Factory - - -#### `new(opts?)` +#### `new(opts?)` {#new} Create a new logger. **Parameters**: -- `opts?` (`mods.log.new.opts`): Logger configuration. +- `opts?` ([`mods.log.new.opts`]): Logger configuration. -**Return**: +**Returns**: -- `logger` (`mods.log.logger`): Logger instance. +- `logger` ([`mods.log.logger`]): Logger instance. -### Logger Methods +--- - +### Logger Methods -#### `debug(...)` +#### `debug(...)` {#debug} Emit a `debug` record. **Parameters**: - `...` (`any`): Additional values joined with spaces. - +--- -#### `error(...)` +#### `error(...)` {#error} Emit an `error` record. **Parameters**: - `...` (`any`): Additional values joined with spaces. - +--- -#### `info(...)` +#### `info(...)` {#info} Emit an `info` record. **Parameters**: - `...` (`any`): Additional values joined with spaces. - +--- -#### `log(levelname, ...)` +#### `log(levelname, ...)` {#log} Emit a record for `level` when it passes the logger filter. **Parameters**: -- `levelname` (`string|"debug"|"info"|"warn"|"error"|"off"`): Log level to emit. +- `levelname` ([`mods.LogLevel`]): Log level to emit. - `...` (`any`): Additional values joined with spaces. - +--- -#### `warn(...)` +#### `warn(...)` {#warn} Emit a `warn` record. **Parameters**: - `...` (`any`): Additional values joined with spaces. + + +[`debug(...)`]: #debug +[`error(...)`]: #error +[`info(...)`]: #info +[`log(levelname, ...)`]: #log +[`mods.LogLevel`]: /mods/types#mods-loglevel +[`mods.log.logger`]: /mods/api/log +[`mods.log.new.opts`]: /mods/api/log +[`new(opts?)`]: #new +[`warn(...)`]: #warn + diff --git a/docs/api/ntpath.md b/docs/api/ntpath.md index cdb218c..2639049 100644 --- a/docs/api/ntpath.md +++ b/docs/api/ntpath.md @@ -1,9 +1,8 @@ --- +title: "ntpath" description: "Windows/NT-style path operations." --- -# `ntpath` - Windows/NT-style path operations. > 💡Python `ntpath`-style behavior, ported to Lua. @@ -11,7 +10,7 @@ Windows/NT-style path operations. ## Usage ```lua -ntpath = require "mods.ntpath" +ntpath = mods.ntpath print(ntpath.join([[C:\]], "Users", "me")) --> "C:\Users\me" print(ntpath.normcase([[A/B\C]])) --> [[a\b\c]] @@ -19,25 +18,23 @@ print(ntpath.splitdrive([[C:\Users\me]])) --> "C:", [[\Users\me]] print(ntpath.isreserved([[C:\Temp\CON.txt]])) --> true ``` -> ✨ Same API as `mods.path`, but with Windows/NT path semantics. +> ✨ Same API as [`mods.path`], but with Windows/NT path semantics. ## Functions - - -### `_expand_percent_vars(p)` +### `_expand_percent_vars(p)` {#expand-percent-vars} Expand percent-style variables in a string. **Parameters**: - `p` (`string`) -**Return**: +**Returns**: - `expanded` (`string`) - +--- -### `ismount(path)` +### `ismount(path)` {#ismount} Return `true` when `path` points to a mount root. @@ -45,7 +42,7 @@ Return `true` when `path` points to a mount root. - `path` (`string`): Path to inspect. -**Return**: +**Returns**: - `isMount` (`boolean`): `true` if the path resolves to a mount root. @@ -55,9 +52,9 @@ Return `true` when `path` points to a mount root. ntpath.ismount([[C:\]]) --> true ``` - +--- -### `isreserved(path)` +### `isreserved(path)` {#isreserved} Return `true` when `path` contains a reserved NT filename. @@ -65,7 +62,7 @@ Return `true` when `path` contains a reserved NT filename. - `path` (`string`): Path to inspect. -**Return**: +**Returns**: - `isReserved` (`boolean`): `true` if any component is NT-reserved. @@ -74,3 +71,7 @@ Return `true` when `path` contains a reserved NT filename. ```lua ntpath.isreserved([[a\CON.txt]]) --> true ``` + + +[`mods.path`]: /mods/api/path + diff --git a/docs/api/operator.md b/docs/api/operator.md index 31670a5..ee91ee0 100644 --- a/docs/api/operator.md +++ b/docs/api/operator.md @@ -1,15 +1,14 @@ --- +title: "operator" description: "Lua operators exposed as functions." --- -# `operator` - Lua operators exposed as functions. ## Usage ```lua -operator = require "mods.operator" +operator = mods.operator print(operator.add(1, 2)) --> 3 ``` @@ -18,56 +17,54 @@ print(operator.add(1, 2)) --> 3 **Arithmetic**: -| Function | Description | -| ------------------------ | --------------------------------------------------------- | -| [`add(a, b)`](#fn-add) | Add two numbers. | -| [`div(a, b)`](#fn-div) | Divide `a` by `b` using Lua's floating-point division. | -| [`idiv(a, b)`](#fn-idiv) | Divide `a` by `b` and return the floor-division quotient. | -| [`mod(a, b)`](#fn-mod) | Return the modulo remainder of `a` divided by `b`. | -| [`mul(a, b)`](#fn-mul) | Multiply two numbers. | -| [`pow(a, b)`](#fn-pow) | Raise `a` to the power of `b`. | -| [`sub(a, b)`](#fn-sub) | Subtract `b` from `a`. | -| [`unm(a)`](#fn-unm) | Negate a number. | +| Function | Description | +| -------------- | --------------------------------------------------------- | +| [`add(a, b)`] | Add two numbers. | +| [`div(a, b)`] | Divide `a` by `b` using Lua's floating-point division. | +| [`idiv(a, b)`] | Divide `a` by `b` and return the floor-division quotient. | +| [`mod(a, b)`] | Return the modulo remainder of `a` divided by `b`. | +| [`mul(a, b)`] | Multiply two numbers. | +| [`pow(a, b)`] | Raise `a` to the power of `b`. | +| [`sub(a, b)`] | Subtract `b` from `a`. | +| [`unm(a)`] | Negate a number. | **Comparison**: -| Function | Description | -| ---------------------- | -------------------------------------------------- | -| [`eq(a, b)`](#fn-eq) | Check whether two values are equal. | -| [`ge(a, b)`](#fn-ge) | Check whether `a` is greater than or equal to `b`. | -| [`gt(a, b)`](#fn-gt) | Check whether `a` is strictly greater than `b`. | -| [`le(a, b)`](#fn-le) | Check whether `a` is less than or equal to `b`. | -| [`lt(a, b)`](#fn-lt) | Check whether `a` is strictly less than `b`. | -| [`neq(a, b)`](#fn-neq) | Check whether two values are not equal. | +| Function | Description | +| ------------- | -------------------------------------------------- | +| [`eq(a, b)`] | Check whether two values are equal. | +| [`ge(a, b)`] | Check whether `a` is greater than or equal to `b`. | +| [`gt(a, b)`] | Check whether `a` is strictly greater than `b`. | +| [`le(a, b)`] | Check whether `a` is less than or equal to `b`. | +| [`lt(a, b)`] | Check whether `a` is strictly less than `b`. | +| [`neq(a, b)`] | Check whether two values are not equal. | **Logical**: -| Function | Description | -| ------------------------ | ---------------------------------------------------- | -| [`land(a, b)`](#fn-land) | Evaluate `a and b` with Lua short-circuit semantics. | -| [`lnot(a)`](#fn-lnot) | Return the boolean negation of `a`. | -| [`lor(a, b)`](#fn-lor) | Evaluate `a or b` with Lua short-circuit semantics. | +| Function | Description | +| -------------- | ---------------------------------------------------- | +| [`land(a, b)`] | Evaluate `a and b` with Lua short-circuit semantics. | +| [`lnot(a)`] | Return the boolean negation of `a`. | +| [`lor(a, b)`] | Evaluate `a or b` with Lua short-circuit semantics. | **String & Length**: -| Function | Description | -| ---------------------------- | ---------------------------------------------------------------- | -| [`concat(a, b)`](#fn-concat) | Concatenate two strings. | -| [`len(a)`](#fn-len) | Return the length of a string or table using Lua's `#` operator. | +| Function | Description | +| ---------------- | ---------------------------------------------------------------- | +| [`concat(a, b)`] | Concatenate two strings. | +| [`len(a)`] | Return the length of a string or table using Lua's `#` operator. | **Tables & Calls**: -| Function | Description | -| ----------------------------------- | -------------------------------------------------------------- | -| [`call(f, ...)`](#fn-call) | Call a function with variadic arguments and return its result. | -| [`index(t, k)`](#fn-index) | Return the value at key/index `k` in table `t`. | -| [`setindex(t, k, v)`](#fn-setindex) | Set `t[k] = v` and return the assigned value. | +| Function | Description | +| --------------------- | -------------------------------------------------------------- | +| [`call(f, ...)`] | Call a function with variadic arguments and return its result. | +| [`index(t, k)`] | Return the value at key/index `k` in table `t`. | +| [`setindex(t, k, v)`] | Set `t[k] = v` and return the assigned value. | ### Arithmetic - - -#### `add(a, b)` +#### `add(a, b)` {#add} Add two numbers. @@ -76,7 +73,7 @@ Add two numbers. - `a` (`number`): Left numeric value. - `b` (`number`): Right numeric value. -**Return**: +**Returns**: - `sum` (`number`): Sum of `a` and `b`. @@ -86,9 +83,9 @@ Add two numbers. add(1, 2) --> 3 ``` - +--- -#### `div(a, b)` +#### `div(a, b)` {#div} Divide `a` by `b` using Lua's floating-point division. @@ -97,7 +94,7 @@ Divide `a` by `b` using Lua's floating-point division. - `a` (`number`): Dividend value. - `b` (`number`): Divisor value. -**Return**: +**Returns**: - `quotient` (`number`): Quotient `a / b`. @@ -107,9 +104,9 @@ Divide `a` by `b` using Lua's floating-point division. div(10, 4) --> 2.5 ``` - +--- -#### `idiv(a, b)` +#### `idiv(a, b)` {#idiv} Divide `a` by `b` and return the floor-division quotient. @@ -118,7 +115,7 @@ Divide `a` by `b` and return the floor-division quotient. - `a` (`number`): Dividend value. - `b` (`number`): Divisor value. -**Return**: +**Returns**: - `quotient` (`integer`): Floor-division result. @@ -128,9 +125,9 @@ Divide `a` by `b` and return the floor-division quotient. idiv(5, 2) --> 2 ``` - +--- -#### `mod(a, b)` +#### `mod(a, b)` {#mod} Return the modulo remainder of `a` divided by `b`. @@ -139,7 +136,7 @@ Return the modulo remainder of `a` divided by `b`. - `a` (`number`): Dividend value. - `b` (`number`): Divisor value. -**Return**: +**Returns**: - `remainder` (`number`): Remainder of `a % b`. @@ -149,9 +146,9 @@ Return the modulo remainder of `a` divided by `b`. mod(5, 2) --> 1 ``` - +--- -#### `mul(a, b)` +#### `mul(a, b)` {#mul} Multiply two numbers. @@ -160,7 +157,7 @@ Multiply two numbers. - `a` (`number`): Left numeric value. - `b` (`number`): Right numeric value. -**Return**: +**Returns**: - `product` (`number`): Product `a * b`. @@ -170,9 +167,9 @@ Multiply two numbers. mul(3, 4) --> 12 ``` - +--- -#### `pow(a, b)` +#### `pow(a, b)` {#pow} Raise `a` to the power of `b`. @@ -181,7 +178,7 @@ Raise `a` to the power of `b`. - `a` (`number`): Base value. - `b` (`number`): Exponent value. -**Return**: +**Returns**: - `power` (`number`): Result of `a ^ b`. @@ -191,9 +188,9 @@ Raise `a` to the power of `b`. pow(2, 4) --> 16 ``` - +--- -#### `sub(a, b)` +#### `sub(a, b)` {#sub} Subtract `b` from `a`. @@ -202,7 +199,7 @@ Subtract `b` from `a`. - `a` (`number`): Left numeric value. - `b` (`number`): Right numeric value. -**Return**: +**Returns**: - `difference` (`number`): Difference `a - b`. @@ -212,9 +209,9 @@ Subtract `b` from `a`. sub(5, 3) --> 2 ``` - +--- -#### `unm(a)` +#### `unm(a)` {#unm} Negate a number. @@ -222,7 +219,7 @@ Negate a number. - `a` (`number`): Input numeric value. -**Return**: +**Returns**: - `negated` (`number`): Result of `-a`. @@ -232,11 +229,11 @@ Negate a number. unm(3) --> -3 ``` -### Comparison +--- - +### Comparison -#### `eq(a, b)` +#### `eq(a, b)` {#eq} Check whether two values are equal. @@ -245,7 +242,7 @@ Check whether two values are equal. - `a` (`any`): Left value. - `b` (`any`): Right value. -**Return**: +**Returns**: - `isEqual` (`boolean`): True when `a == b`. @@ -255,9 +252,9 @@ Check whether two values are equal. eq(1, 1) --> true ``` - +--- -#### `ge(a, b)` +#### `ge(a, b)` {#ge} Check whether `a` is greater than or equal to `b`. @@ -266,7 +263,7 @@ Check whether `a` is greater than or equal to `b`. - `a` (`number`): Left numeric value. - `b` (`number`): Right numeric value. -**Return**: +**Returns**: - `isGreaterOrEqual` (`boolean`): True when `a >= b`. @@ -276,9 +273,9 @@ Check whether `a` is greater than or equal to `b`. ge(2, 2) --> true ``` - +--- -#### `gt(a, b)` +#### `gt(a, b)` {#gt} Check whether `a` is strictly greater than `b`. @@ -287,7 +284,7 @@ Check whether `a` is strictly greater than `b`. - `a` (`number`): Left numeric value. - `b` (`number`): Right numeric value. -**Return**: +**Returns**: - `isGreater` (`boolean`): True when `a > b`. @@ -297,9 +294,9 @@ Check whether `a` is strictly greater than `b`. gt(3, 2) --> true ``` - +--- -#### `le(a, b)` +#### `le(a, b)` {#le} Check whether `a` is less than or equal to `b`. @@ -308,7 +305,7 @@ Check whether `a` is less than or equal to `b`. - `a` (`number`): Left numeric value. - `b` (`number`): Right numeric value. -**Return**: +**Returns**: - `isLessOrEqual` (`boolean`): True when `a <= b`. @@ -318,9 +315,9 @@ Check whether `a` is less than or equal to `b`. le(2, 2) --> true ``` - +--- -#### `lt(a, b)` +#### `lt(a, b)` {#lt} Check whether `a` is strictly less than `b`. @@ -329,7 +326,7 @@ Check whether `a` is strictly less than `b`. - `a` (`number`): Left numeric value. - `b` (`number`): Right numeric value. -**Return**: +**Returns**: - `isLess` (`boolean`): True when `a < b`. @@ -339,9 +336,9 @@ Check whether `a` is strictly less than `b`. lt(1, 2) --> true ``` - +--- -#### `neq(a, b)` +#### `neq(a, b)` {#neq} Check whether two values are not equal. @@ -350,7 +347,7 @@ Check whether two values are not equal. - `a` (`any`): Left value. - `b` (`any`): Right value. -**Return**: +**Returns**: - `isNotEqual` (`boolean`): True when `a ~= b`. @@ -360,11 +357,11 @@ Check whether two values are not equal. neq(1, 2) --> true ``` -### Logical +--- - +### Logical -#### `land(a, b)` +#### `land(a, b)` {#land} Evaluate `a and b` with Lua short-circuit semantics. @@ -373,9 +370,9 @@ Evaluate `a and b` with Lua short-circuit semantics. - `a` (`T1`): First operand. - `b` (`T2`): Second operand. -**Return**: +**Returns**: -- `andValue` (`T1|T2`): Result of `a and b`. +- `andValue` (`T1` | `T2`): Result of `a and b`. **Example**: @@ -383,9 +380,9 @@ Evaluate `a and b` with Lua short-circuit semantics. land(true, false) --> false ``` - +--- -#### `lnot(a)` +#### `lnot(a)` {#lnot} Return the boolean negation of `a`. @@ -393,7 +390,7 @@ Return the boolean negation of `a`. - `a` (`any`): Input value. -**Return**: +**Returns**: - `isNot` (`boolean`): Result of `not a`. @@ -403,9 +400,9 @@ Return the boolean negation of `a`. lnot(true) --> false ``` - +--- -#### `lor(a, b)` +#### `lor(a, b)` {#lor} Evaluate `a or b` with Lua short-circuit semantics. @@ -414,9 +411,9 @@ Evaluate `a or b` with Lua short-circuit semantics. - `a` (`T1`): First operand. - `b` (`T2`): Second operand. -**Return**: +**Returns**: -- `orValue` (`T1|T2`): Result of `a or b`. +- `orValue` (`T1` | `T2`): Result of `a or b`. **Example**: @@ -424,11 +421,11 @@ Evaluate `a or b` with Lua short-circuit semantics. lor(false, true) --> true ``` -### String & Length +--- - +### String & Length -#### `concat(a, b)` +#### `concat(a, b)` {#concat} Concatenate two strings. @@ -437,7 +434,7 @@ Concatenate two strings. - `a` (`string`): Left string. - `b` (`string`): Right string. -**Return**: +**Returns**: - `concatenated` (`string`): Concatenated result `a .. b`. @@ -447,17 +444,17 @@ Concatenate two strings. concat("a", "b") --> "ab" ``` - +--- -#### `len(a)` +#### `len(a)` {#len} Return the length of a string or table using Lua's `#` operator. **Parameters**: -- `a` (`string|table`): Value supporting Lua's `#` operator. +- `a` (`string` | `table`): Value supporting Lua's `#` operator. -**Return**: +**Returns**: - `length` (`integer`): Length computed by `#a`. @@ -467,11 +464,11 @@ Return the length of a string or table using Lua's `#` operator. len("abc") --> 3 ``` -### Tables & Calls +--- - +### Tables & Calls -#### `call(f, ...)` +#### `call(f, ...)` {#call} Call a function with variadic arguments and return its result. @@ -480,7 +477,7 @@ Call a function with variadic arguments and return its result. - `f` (`fun(...:T1):T2`): Function to call. - `...` (`T1`): Additional arguments. -**Return**: +**Returns**: - `callResult` (`T2`): Return value(s) from `f(...)`. @@ -490,9 +487,9 @@ Call a function with variadic arguments and return its result. call(math.max, 1, 2) --> 2 ``` - +--- -#### `index(t, k)` +#### `index(t, k)` {#index} Return the value at key/index `k` in table `t`. @@ -501,7 +498,7 @@ Return the value at key/index `k` in table `t`. - `t` (`table`): Source table. - `k` (`T`): Key/index value. -**Return**: +**Returns**: - `indexedValue` (`T`): Value stored at `t[k]`. @@ -511,9 +508,9 @@ Return the value at key/index `k` in table `t`. index({ a = 1 }, "a") --> 1 ``` - +--- -#### `setindex(t, k, v)` +#### `setindex(t, k, v)` {#setindex} Set `t[k] = v` and return the assigned value. @@ -523,7 +520,7 @@ Set `t[k] = v` and return the assigned value. - `k` (`any`): Key/index value. - `v` (`T`): Value to set. -**Return**: +**Returns**: - `assignedValue` (`T`): Assigned value `v`. @@ -532,3 +529,28 @@ Set `t[k] = v` and return the assigned value. ```lua setindex({}, "a", 1) --> 1 ``` + + +[`add(a, b)`]: #add +[`call(f, ...)`]: #call +[`concat(a, b)`]: #concat +[`div(a, b)`]: #div +[`eq(a, b)`]: #eq +[`ge(a, b)`]: #ge +[`gt(a, b)`]: #gt +[`idiv(a, b)`]: #idiv +[`index(t, k)`]: #index +[`land(a, b)`]: #land +[`le(a, b)`]: #le +[`len(a)`]: #len +[`lnot(a)`]: #lnot +[`lor(a, b)`]: #lor +[`lt(a, b)`]: #lt +[`mod(a, b)`]: #mod +[`mul(a, b)`]: #mul +[`neq(a, b)`]: #neq +[`pow(a, b)`]: #pow +[`setindex(t, k, v)`]: #setindex +[`sub(a, b)`]: #sub +[`unm(a)`]: #unm + diff --git a/docs/api/path.md b/docs/api/path.md index 1e52564..a39862a 100644 --- a/docs/api/path.md +++ b/docs/api/path.md @@ -1,15 +1,14 @@ --- +title: "path" description: "Cross-platform path operations with host-platform semantics." --- -# `path` - Cross-platform path operations with host-platform semantics. ## Usage ```lua -path = require "mods.path" +path = mods.path print(path.join("src", "mods", "path.lua")) --> "src/mods/path.lua" print(path.normpath("a//b/./c")) --> "a/b/c" @@ -18,86 +17,84 @@ print(path.splitext("archive.tar.gz")) --> "archive.tar", ".gz" ## Functions -| Function | Description | -| ------------------------------------------------------- | ---------------------------- | -| [`_splitext(path, sep, altsep?, extsep)`](#fn-splitext) | Split extension from a path. | +| Function | Description | +| ----------------------------------------- | ---------------------------- | +| [`_splitext(path, sep, altsep?, extsep)`] | Split extension from a path. | **Anchors**: -| Function | Description | -| ---------------------------- | ------------------------------------------- | -| [`anchor(path)`](#fn-anchor) | Return drive and root combined. | -| [`drive(path)`](#fn-drive) | Return drive prefix when present. | -| [`root(path)`](#fn-root) | Return root separator segment when present. | +| Function | Description | +| ---------------- | ------------------------------------------- | +| [`anchor(path)`] | Return drive and root combined. | +| [`drive(path)`] | Return drive prefix when present. | +| [`root(path)`] | Return root separator segment when present. | **Components**: -| Function | Description | -| -------------------------------- | ------------------------------------------------------------- | -| [`parents(path)`](#fn-parents) | Return logical parent paths from nearest to farthest. | -| [`parts(path)`](#fn-parts) | Split path into logical parts, including anchor when present. | -| [`stem(path)`](#fn-stem) | Return filename without its final suffix. | -| [`suffixes(path)`](#fn-suffixes) | Return all filename suffixes in order. | +| Function | Description | +| ------------------ | ------------------------------------------------------------- | +| [`parents(path)`] | Return logical parent paths from nearest to farthest. | +| [`parts(path)`] | Split path into logical parts, including anchor when present. | +| [`stem(path)`] | Return filename without its final suffix. | +| [`suffixes(path)`] | Return all filename suffixes in order. | **Conversions**: -| Function | Description | -| -------------------------------- | --------------------------------------------------- | -| [`as_posix(path)`](#fn-as-posix) | Convert backslashes (`\`) to forward slashes (`/`). | -| [`as_uri(path)`](#fn-as-uri) | Convert a local path to a `file://` URI. | -| [`from_uri(uri)`](#fn-from-uri) | Convert a `file://` URI to a local absolute path. | +| Function | Description | +| ------------------ | --------------------------------------------------- | +| [`as_posix(path)`] | Convert backslashes (`\`) to forward slashes (`/`). | +| [`as_uri(path)`] | Convert a local path to a `file://` URI. | +| [`from_uri(uri)`] | Convert a `file://` URI to a local absolute path. | **Decomposition**: -| Function | Description | -| ------------------------------------ | -------------------------------------------------- | -| [`basename(path)`](#fn-basename) | Return final path component. | -| [`dirname(path)`](#fn-dirname) | Return directory portion of a path. | -| [`split(path)`](#fn-split) | Split path into directory head and tail component. | -| [`splitdrive(path)`](#fn-splitdrive) | Split drive prefix from remainder. | -| [`splitext(path)`](#fn-splitext) | Split path into a root and extension. | -| [`splitroot(path)`](#fn-splitroot) | Split path into drive, root, and tail components. | +| Function | Description | +| -------------------- | -------------------------------------------------- | +| [`basename(path)`] | Return final path component. | +| [`dirname(path)`] | Return directory portion of a path. | +| [`split(path)`] | Split path into directory head and tail component. | +| [`splitdrive(path)`] | Split drive prefix from remainder. | +| [`splitext(path)`] | Split path into a root and extension. | +| [`splitroot(path)`] | Split path into drive, root, and tail components. | **Derived**: -| Function | Description | -| ----------------------------------------- | ------------------------------------------------ | -| [`abspath(path)`](#fn-abspath) | Return normalized absolute path. | -| [`commonpath(paths)`](#fn-commonpath) | Return longest common sub-path from a path list. | -| [`commonprefix(paths)`](#fn-commonprefix) | Return longest common leading string prefix. | -| [`relpath(path, start?)`](#fn-relpath) | Return `path` relative to optional `start` path. | +| Function | Description | +| ------------------------- | ------------------------------------------------ | +| [`abspath(path)`] | Return normalized absolute path. | +| [`commonpath(paths)`] | Return longest common sub-path from a path list. | +| [`commonprefix(paths)`] | Return longest common leading string prefix. | +| [`relpath(path, start?)`] | Return `path` relative to optional `start` path. | **Environment**: -| Function | Description | -| ------------------------------------ | ----------------------------------------------------------------------- | -| `cwd` | Return the current working directory path. | -| [`expanduser(path)`](#fn-expanduser) | Expand `~` home segment when available. | -| [`expandvars(path)`](#fn-expandvars) | Expand vars in a path (`$VAR`/`${VAR}` everywhere, `%VAR%` on Windows). | -| [`home()`](#fn-home) | Return the current user's home directory path. | +| Function | Description | +| -------------------- | ----------------------------------------------------------------------- | +| `cwd` | Return the current working directory path. | +| [`expanduser(path)`] | Expand `~` home segment when available. | +| [`expandvars(path)`] | Expand vars in a path (`$VAR`/`${VAR}` everywhere, `%VAR%` on Windows). | +| [`home()`] | Return the current user's home directory path. | **Normalization**: -| Function | Description | -| -------------------------------- | ---------------------------------------------------- | -| [`isabs(path)`](#fn-isabs) | Return `true` when `path` is absolute. | -| [`join(path, ...)`](#fn-join) | Join path components. | -| [`normcase(s)`](#fn-normcase) | Normalize path case using the active path semantics. | -| [`normpath(path)`](#fn-normpath) | Normalize separators and dot segments. | +| Function | Description | +| ------------------- | ---------------------------------------------------- | +| [`isabs(path)`] | Return `true` when `path` is absolute. | +| [`join(path, ...)`] | Join path components. | +| [`normcase(s)`] | Normalize path case using the active path semantics. | +| [`normpath(path)`] | Normalize separators and dot segments. | **Relations**: -| Function | Description | -| ------------------------------------------------------- | --------------------------------------------------------------------------------------- | -| [`is_relative_to(path, other)`](#fn-is-relative-to) | Return `true` when `path` is under `other`. | -| [`relative_to(path, other, walk_up?)`](#fn-relative-to) | Return `path` relative to `other`, or `nil` with an error when it is not under `other`. | -| [`with_name(path, name)`](#fn-with-name) | Return a path with the final filename replaced. | -| [`with_stem(path, stem)`](#fn-with-stem) | Return a path with the final filename stem replaced. | -| [`with_suffix(path, suffix)`](#fn-with-suffix) | Return a path with the final filename suffix replaced. | - - +| Function | Description | +| -------------------------------------- | --------------------------------------------------------------------------------------- | +| [`is_relative_to(path, other)`] | Return `true` when `path` is under `other`. | +| [`relative_to(path, other, walk_up?)`] | Return `path` relative to `other`, or `nil` with an error when it is not under `other`. | +| [`with_name(path, name)`] | Return a path with the final filename replaced. | +| [`with_stem(path, stem)`] | Return a path with the final filename stem replaced. | +| [`with_suffix(path, suffix)`] | Return a path with the final filename suffix replaced. | -### `_splitext(path, sep, altsep?, extsep)` +### `_splitext(path, sep, altsep?, extsep)` {#splitext} Split extension from a path. **Parameters**: @@ -106,16 +103,16 @@ Split extension from a path. **Parameters**: - `altsep?` (`string`) - `extsep` (`string`) -**Return**: +**Returns**: - `root` (`string`) - `ext` (`string`) -### Anchors +--- - +### Anchors -#### `anchor(path)` +#### `anchor(path)` {#anchor} Return drive and root combined. @@ -123,7 +120,7 @@ Return drive and root combined. - `path` (`string`): Input path. -**Return**: +**Returns**: - `anchor` (`string`): Drive and root anchor. @@ -133,9 +130,9 @@ Return drive and root combined. path.anchor("c:\\") --> "c:\\" ``` - +--- -#### `drive(path)` +#### `drive(path)` {#drive} Return drive prefix when present. @@ -143,7 +140,7 @@ Return drive prefix when present. - `path` (`string`): Input path. -**Return**: +**Returns**: - `drivePrefix` (`string`): Drive prefix. @@ -154,9 +151,9 @@ path.drive("c:a/b") --> "c:" path.drive("a/b") --> "" ``` - +--- -#### `root(path)` +#### `root(path)` {#root} Return root separator segment when present. @@ -164,7 +161,7 @@ Return root separator segment when present. - `path` (`string`): Input path. -**Return**: +**Returns**: - `rootSeparator` (`string`): Root separator segment. @@ -176,11 +173,11 @@ path.root("c:/") --> "\\" path.root("a/b") --> "" ``` -### Components +--- - +### Components -#### `parents(path)` +#### `parents(path)` {#parents} Return logical parent paths from nearest to farthest. @@ -188,9 +185,9 @@ Return logical parent paths from nearest to farthest. - `path` (`string`): Input path. -**Return**: +**Returns**: -- `parents` (`mods.List`): Ancestor paths from nearest to farthest. +- `parents` ([`mods.List`]``): Ancestor paths from nearest to farthest. **Example**: @@ -199,9 +196,9 @@ path.parents("a/b/c") --> {"a/b", "a", "."} path.parents("c:a/b") --> {"c:a", "c:"} ``` - +--- -#### `parts(path)` +#### `parts(path)` {#parts} Split path into logical parts, including anchor when present. @@ -209,9 +206,9 @@ Split path into logical parts, including anchor when present. - `path` (`string`): Input path. -**Return**: +**Returns**: -- `paths` (`mods.List`): Path parts including anchor when present. +- `paths` ([`mods.List`]``): Path parts including anchor when present. **Example**: @@ -221,9 +218,9 @@ path.parts("/a/b") --> {"/", "a", "b"} path.parts("c:a\\b") --> {"c:", "a", "b"} ``` - +--- -#### `stem(path)` +#### `stem(path)` {#stem} Return filename without its final suffix. @@ -231,7 +228,7 @@ Return filename without its final suffix. - `path` (`string`): Input path. -**Return**: +**Returns**: - `stem` (`string`): Filename stem. @@ -242,9 +239,9 @@ path.stem("archive.tar.gz") --> "archive.tar" path.stem("c:a/b") --> "b" ``` - +--- -#### `suffixes(path)` +#### `suffixes(path)` {#suffixes} Return all filename suffixes in order. @@ -252,9 +249,9 @@ Return all filename suffixes in order. - `path` (`string`): Input path. -**Return**: +**Returns**: -- `suffixes` (`mods.List`): Filename suffixes. +- `suffixes` ([`mods.List`]``): Filename suffixes. **Example**: @@ -263,11 +260,11 @@ path.suffixes("archive.tar.gz") --> {".tar", ".gz"} path.suffixes("a/b") --> {} ``` -### Conversions +--- - +### Conversions -#### `as_posix(path)` +#### `as_posix(path)` {#as-posix} Convert backslashes (`\`) to forward slashes (`/`). @@ -275,7 +272,7 @@ Convert backslashes (`\`) to forward slashes (`/`). - `path` (`string`): Input path. -**Return**: +**Returns**: - `posixPath` (`string`): POSIX-style path. @@ -285,9 +282,9 @@ Convert backslashes (`\`) to forward slashes (`/`). path.as_posix("a\\b\\c") --> "a/b/c" ``` - +--- -#### `as_uri(path)` +#### `as_uri(path)` {#as-uri} Convert a local path to a `file://` URI. @@ -295,10 +292,10 @@ Convert a local path to a `file://` URI. - `path` (`string`): Input path. -**Return**: +**Returns**: -- `fileUri` (`string?`): File URI. -- `err` (`string?`): Error message when conversion fails. +- `fileUri?` (`string`): File URI. +- `err?` (`string`): Error message when conversion fails. **Example**: @@ -308,9 +305,9 @@ path.as_uri("c:/a/b.c") --> "file:///c:/a/b.c" path.as_uri("/a/b%#c") --> "file:///a/b%25%23c" ``` - +--- -#### `from_uri(uri)` +#### `from_uri(uri)` {#from-uri} Convert a `file://` URI to a local absolute path. @@ -318,10 +315,10 @@ Convert a `file://` URI to a local absolute path. - `uri` (`string`): URI value. -**Return**: +**Returns**: -- `path` (`string?`): Resolved absolute path. -- `err` (`string?`): Error message when conversion fails. +- `path?` (`string`): Resolved absolute path. +- `err?` (`string`): Error message when conversion fails. **Example**: @@ -329,11 +326,11 @@ Convert a `file://` URI to a local absolute path. path.from_uri("file://localhost/tmp/a.txt") --> "/tmp/a.txt" ``` -### Decomposition +--- - +### Decomposition -#### `basename(path)` +#### `basename(path)` {#basename} Return final path component. @@ -341,7 +338,7 @@ Return final path component. - `path` (`string`): Path to inspect. -**Return**: +**Returns**: - `basename` (`string`): Final path component. @@ -352,9 +349,9 @@ path.basename("/a/b.txt") --> "b.txt" path.basename([[C:\a\b.txt]]) --> "b.txt" ``` - +--- -#### `dirname(path)` +#### `dirname(path)` {#dirname} Return directory portion of a path. @@ -362,7 +359,7 @@ Return directory portion of a path. - `path` (`string`): Path to inspect. -**Return**: +**Returns**: - `dirname` (`string`): Parent directory path. @@ -373,9 +370,9 @@ path.dirname("/a/b.txt") --> "/a" path.dirname([[C:\a\b.txt]]) --> [[C:\a]] ``` - +--- -#### `split(path)` +#### `split(path)` {#split} Split path into directory head and tail component. @@ -383,7 +380,7 @@ Split path into directory head and tail component. - `path` (`string`): Input path. -**Return**: +**Returns**: - `head` (`string`): Directory portion. - `tail` (`string`): Final path component. @@ -394,9 +391,9 @@ Split path into directory head and tail component. path.split("/a/b.txt") --> "/a", "b.txt" ``` - +--- -#### `splitdrive(path)` +#### `splitdrive(path)` {#splitdrive} Split drive prefix from remainder. @@ -404,7 +401,7 @@ Split drive prefix from remainder. - `path` (`string`): Input path. -**Return**: +**Returns**: - `drive` (`string`): Drive or share prefix when present. - `rest` (`string`): Path remainder. @@ -419,9 +416,9 @@ path.splitdrive("/a/b") --> "", "/a/b" > > On POSIX semantics the drive portion is always empty. - +--- -#### `splitext(path)` +#### `splitext(path)` {#splitext-1} Split path into a root and extension. @@ -429,7 +426,7 @@ Split path into a root and extension. - `path` (`string`): Input path. -**Return**: +**Returns**: - `root` (`string`): Path without the final extension. - `ext` (`string`): Final extension including leading dot. @@ -440,9 +437,9 @@ Split path into a root and extension. path.splitext("archive.tar.gz") --> "archive.tar", ".gz" ``` - +--- -#### `splitroot(path)` +#### `splitroot(path)` {#splitroot} Split path into drive, root, and tail components. @@ -450,7 +447,7 @@ Split path into drive, root, and tail components. - `path` (`string`): Path to split. -**Return**: +**Returns**: - `drive` (`string`): Drive or share prefix (empty on POSIX). - `root` (`string`): Root separator segment. @@ -463,11 +460,11 @@ path.splitroot("/a/b") --> "", "/", "a/b" path.splitroot([[C:\a\b]]) --> "C:", [[\]], "a\\b" ``` -### Derived +--- - +### Derived -#### `abspath(path)` +#### `abspath(path)` {#abspath} Return normalized absolute path. @@ -475,7 +472,7 @@ Return normalized absolute path. - `path` (`string`): Path to absolutize. -**Return**: +**Returns**: - `absolutePath` (`string`): Absolute normalized path. @@ -486,9 +483,9 @@ path.abspath("/a/./b") --> "/a/b" path.abspath([[C:\a\..\b]]) --> [[C:\b]] ``` - +--- -#### `commonpath(paths)` +#### `commonpath(paths)` {#commonpath} Return longest common sub-path from a path list. @@ -496,10 +493,10 @@ Return longest common sub-path from a path list. - `paths` (`string[]`): List of paths. -**Return**: +**Returns**: -- `commonPath` (`string?`): Longest common sub-path. -- `err` (`string?`): Error message when inputs are incompatible. +- `commonPath?` (`string`): Longest common sub-path. +- `err?` (`string`): Error message when inputs are incompatible. **Example**: @@ -508,9 +505,9 @@ path.commonpath({ "/a/b/c", "/a/b/d" }) --> "/a/b" path.commonpath({ [[C:\a\b\c]], [[c:/a/b/d]] }) --> [[C:\a\b]] ``` - +--- -#### `commonprefix(paths)` +#### `commonprefix(paths)` {#commonprefix} Return longest common leading string prefix. @@ -518,7 +515,7 @@ Return longest common leading string prefix. - `paths` (`string[]`): List of paths. -**Return**: +**Returns**: - `commonPrefix` (`string`): Longest common string prefix. @@ -530,9 +527,9 @@ path.commonprefix({"/home/swen/spam", "/home/swen/eggs"}) --> "/home/swen/" path.commonprefix({"abc", "xyz"}) --> "" ``` - +--- -#### `relpath(path, start?)` +#### `relpath(path, start?)` {#relpath} Return `path` relative to optional `start` path. @@ -541,10 +538,10 @@ Return `path` relative to optional `start` path. - `path` (`string`): Input path. - `start?` (`string`): Optional base path. -**Return**: +**Returns**: -- `relativePath` (`string?`): Relative path from `start` to `path`. -- `err` (`string?`): Error message when the path cannot be made relative. +- `relativePath?` (`string`): Relative path from `start` to `path`. +- `err?` (`string`): Error message when the path cannot be made relative. **Example**: @@ -553,15 +550,15 @@ path.relpath("/a/b/c", "/a") --> "b/c" path.relpath([[C:\a\b\c]], [[C:\a]]) --> [[b\c]] ``` -### Environment +--- - +### Environment -#### `cwd` +#### `cwd` {#cwd} -Return the current working directory path. +## Return the current working directory path. -#### `expanduser(path)` +#### `expanduser(path)` {#expanduser} Expand `~` home segment when available. @@ -569,11 +566,11 @@ Expand `~` home segment when available. - `path` (`string`): Path that may begin with `~`. -**Return**: +**Returns**: -- `expandedPath` (`string?`): Path with the home segment expanded when +- `expandedPath?` (`string`): Path with the home segment expanded when available. -- `err` (`string?`): Error message when `~` expansion cannot be resolved. +- `err?` (`string`): Error message when `~` expansion cannot be resolved. **Example**: @@ -582,9 +579,9 @@ path.expanduser("~/tmp") --> "/tmp" (when HOME is set) path.expanduser([[x\y]]) --> [[x\y]] ``` - +--- -#### `expandvars(path)` +#### `expandvars(path)` {#expandvars} Expand vars in a path (`$VAR`/`${VAR}` everywhere, `%VAR%` on Windows). @@ -592,7 +589,7 @@ Expand vars in a path (`$VAR`/`${VAR}` everywhere, `%VAR%` on Windows). - `path` (`string`): Path containing variable placeholders. -**Return**: +**Returns**: - `expandedPath` (`string`): Path with variable values substituted. @@ -605,16 +602,16 @@ path.expandvars("%USERPROFILE%\\bin") --> "C:\\Users\\me\\bin" path.expandvars("$UNKNOWN/bin") --> "$UNKNOWN/bin" ``` - +--- -#### `home()` +#### `home()` {#home} Return the current user's home directory path. -**Return**: +**Returns**: -- `homePath` (`string?`): Home directory path when available. -- `err` (`string?`): Error message when the home directory cannot be resolved. +- `homePath?` (`string`): Home directory path when available. +- `err?` (`string`): Error message when the home directory cannot be resolved. **Example**: @@ -622,11 +619,11 @@ Return the current user's home directory path. path.home() ``` -### Normalization +--- - +### Normalization -#### `isabs(path)` +#### `isabs(path)` {#isabs} Return `true` when `path` is absolute. @@ -634,7 +631,7 @@ Return `true` when `path` is absolute. - `path` (`string`): Input path. -**Return**: +**Returns**: - `isAbsolute` (`boolean`): True when `path` is absolute. @@ -644,9 +641,9 @@ Return `true` when `path` is absolute. path.isabs("/a/b") --> true ``` - +--- -#### `join(path, ...)` +#### `join(path, ...)` {#join} Join path components. @@ -655,7 +652,7 @@ Join path components. - `path` (`string`): Base path component. - `...` (`string`): Additional path components. -**Return**: +**Returns**: - `joinedPath` (`string`): Joined path. @@ -670,9 +667,9 @@ path.join([[C:/a]], [[b]]) --> [[C:/a\b]] > > Single input is returned as-is. - +--- -#### `normcase(s)` +#### `normcase(s)` {#normcase} Normalize path case using the active path semantics. @@ -680,7 +677,7 @@ Normalize path case using the active path semantics. - `s` (`string`): Input path value. -**Return**: +**Returns**: - `normalizedPath` (`string`): Path after case normalization. @@ -693,12 +690,12 @@ path.normcase("/A/B") --> "\\a\\b" > [!NOTE] > -> On POSIX semantics this returns the input unchanged. Use `mods.ntpath` to +> On POSIX semantics this returns the input unchanged. Use [`mods.ntpath`] to > force Windows-style case folding and separator normalization. - +--- -#### `normpath(path)` +#### `normpath(path)` {#normpath} Normalize separators and dot segments. @@ -706,7 +703,7 @@ Normalize separators and dot segments. - `path` (`string`): Path to normalize. -**Return**: +**Returns**: - `normalizedPath` (`string`): Normalized path. @@ -717,11 +714,11 @@ path.normpath("/a//./b/..") --> "/a" path.normpath([[A/foo/../B]]) --> [[A\B]] ``` -### Relations +--- - +### Relations -#### `is_relative_to(path, other)` +#### `is_relative_to(path, other)` {#is-relative-to} Return `true` when `path` is under `other`. @@ -730,7 +727,7 @@ Return `true` when `path` is under `other`. - `path` (`string`): Input path. - `other` (`string`): Reference path. -**Return**: +**Returns**: - `isRelative` (`boolean`): True when `path` is under `other`. @@ -742,9 +739,9 @@ path.is_relative_to("C:A/B", "c:a") --> true path.is_relative_to("a/b", "a/b/c") --> false ``` - +--- -#### `relative_to(path, other, walk_up?)` +#### `relative_to(path, other, walk_up?)` {#relative-to} Return `path` relative to `other`, or `nil` with an error when it is not under `other`. @@ -757,10 +754,10 @@ When `walk_up` is `true`, allow `..` segments to walk up to a shared prefix. - `other` (`string`): Reference path. - `walk_up?` (`boolean`): Allow walking up to a shared prefix. -**Return**: +**Returns**: -- `relativePath` (`string?`): Path relative to `other`, or `nil` on error. -- `err` (`string?`): Error message when the path cannot be made relative. +- `relativePath?` (`string`): Path relative to `other`, or `nil` on error. +- `err?` (`string`): Error message when the path cannot be made relative. **Example**: @@ -770,9 +767,9 @@ path.relative_to("/a/b", "/a/c", true) --> "../b" path.relative_to("/a/b", "/a/x") --> nil, "'/a/b' is not in the subpath of '/a/x'" ``` - +--- -#### `with_name(path, name)` +#### `with_name(path, name)` {#with-name} Return a path with the final filename replaced. @@ -781,10 +778,10 @@ Return a path with the final filename replaced. - `path` (`string`): Input path. - `name` (`string`): Replacement filename. -**Return**: +**Returns**: -- `updatedPath` (`string?`): Path with replaced filename, or `nil` on error. -- `err` (`string?`): Error message when replacement fails. +- `updatedPath?` (`string`): Path with replaced filename, or `nil` on error. +- `err?` (`string`): Error message when replacement fails. **Example**: @@ -795,9 +792,9 @@ path.with_name("a/b", "c/d") --> nil, "invalid name 'c/d'" path.with_name("/", "d.xml") --> nil, "'/' has an empty name" ``` - +--- -#### `with_stem(path, stem)` +#### `with_stem(path, stem)` {#with-stem} Return a path with the final filename stem replaced. @@ -806,11 +803,11 @@ Return a path with the final filename stem replaced. - `path` (`string`): Input path. - `stem` (`string`): Replacement filename stem. -**Return**: +**Returns**: -- `updatedPath` (`string?`): Path with replaced filename stem, or `nil` on +- `updatedPath?` (`string`): Path with replaced filename stem, or `nil` on error. -- `err` (`string?`): Error message when replacement fails. +- `err?` (`string`): Error message when replacement fails. **Example**: @@ -821,9 +818,9 @@ path.with_stem("/", "d") --> "'/' has an empty name" path.with_stem("a/b", "d") --> "invalid name ''." ``` - +--- -#### `with_suffix(path, suffix)` +#### `with_suffix(path, suffix)` {#with-suffix} Return a path with the final filename suffix replaced. @@ -832,10 +829,10 @@ Return a path with the final filename suffix replaced. - `path` (`string`): Input path. - `suffix` (`string`): Replacement suffix. -**Return**: +**Returns**: -- `updatedPath` (`string?`): Path with replaced suffix, or `nil` on error. -- `err` (`string?`): Error message when replacement fails. +- `updatedPath?` (`string`): Path with replaced suffix, or `nil` on error. +- `err?` (`string`): Error message when replacement fails. **Example**: @@ -845,3 +842,41 @@ path.with_suffix("a/b.gz", ".lua") --> "a/b/.lua" path.with_suffix("a/b", "gz") --> nil, "invalid suffix 'gz'" path.with_suffix("//a/b", "gz") --> nil, "'//a/b' has an empty name" ``` + + +[`_splitext(path, sep, altsep?, extsep)`]: #splitext +[`abspath(path)`]: #abspath +[`anchor(path)`]: #anchor +[`as_posix(path)`]: #as-posix +[`as_uri(path)`]: #as-uri +[`basename(path)`]: #basename +[`commonpath(paths)`]: #commonpath +[`commonprefix(paths)`]: #commonprefix +[`dirname(path)`]: #dirname +[`drive(path)`]: #drive +[`expanduser(path)`]: #expanduser +[`expandvars(path)`]: #expandvars +[`from_uri(uri)`]: #from-uri +[`home()`]: #home +[`is_relative_to(path, other)`]: #is-relative-to +[`isabs(path)`]: #isabs +[`join(path, ...)`]: #join +[`mods.List`]: /mods/api/list +[`mods.ntpath`]: /mods/api/ntpath +[`normcase(s)`]: #normcase +[`normpath(path)`]: #normpath +[`parents(path)`]: #parents +[`parts(path)`]: #parts +[`relative_to(path, other, walk_up?)`]: #relative-to +[`relpath(path, start?)`]: #relpath +[`root(path)`]: #root +[`split(path)`]: #split +[`splitdrive(path)`]: #splitdrive +[`splitext(path)`]: #splitext-1 +[`splitroot(path)`]: #splitroot +[`stem(path)`]: #stem +[`suffixes(path)`]: #suffixes +[`with_name(path, name)`]: #with-name +[`with_stem(path, stem)`]: #with-stem +[`with_suffix(path, suffix)`]: #with-suffix + diff --git a/docs/api/posixpath.md b/docs/api/posixpath.md index 31d90cc..14de3b7 100644 --- a/docs/api/posixpath.md +++ b/docs/api/posixpath.md @@ -1,9 +1,8 @@ --- +title: "posixpath" description: "POSIX-style path operations." --- -# `posixpath` - POSIX-style path operations. > 💡 Python `posixpath`-style behavior, ported to Lua. @@ -11,7 +10,7 @@ POSIX-style path operations. ## Usage ```lua -posixpath = require "mods.posixpath" +posixpath = mods.posixpath print(posixpath.join("/usr", "bin")) --> "/usr/bin" print(posixpath.normpath("/a//./b/..")) --> "/a" @@ -19,4 +18,8 @@ print(posixpath.splitext("archive.tar.gz")) --> "archive.tar", ".gz" print(posixpath.relpath("/usr/local/bin", "/usr")) --> "local/bin" ``` -> ✨ Same API as `mods.path`, but with POSIX path semantics. +> ✨ Same API as [`mods.path`], but with POSIX path semantics. + + +[`mods.path`]: /mods/api/path + diff --git a/docs/api/runtime.md b/docs/api/runtime.md index 805d576..877056d 100644 --- a/docs/api/runtime.md +++ b/docs/api/runtime.md @@ -1,15 +1,14 @@ --- +title: "runtime" description: "Lua runtime metadata and version compatibility flags." --- -# `runtime` - Lua runtime metadata and version compatibility flags. ## Usage ```lua -runtime = require "mods.runtime" +runtime = mods.runtime print(runtime.version) --> 501 | 502 | 503 | 504 | 505 print(runtime.is_lua55) --> true | false @@ -17,22 +16,20 @@ print(runtime.is_lua55) --> true | false ## Fields -| Field | Description | -| --------------------------- | ------------------------------------------------- | -| [`is_lua51`](#is-lua51) | True only on Lua 5.1 runtimes. | -| [`is_lua52`](#is-lua52) | True only on Lua 5.2 runtimes. | -| [`is_lua53`](#is-lua53) | True only on Lua 5.3 runtimes. | -| [`is_lua54`](#is-lua54) | True only on Lua 5.4 runtimes. | -| [`is_lua55`](#is-lua55) | True only on Lua 5.5 runtimes. | -| [`is_luajit`](#is-luajit) | True when running under LuaJIT. | -| [`is_windows`](#is-windows) | True when running on a Windows host. | -| [`major`](#major) | Major version number parsed from `version`. | -| [`minor`](#minor) | Minor version number parsed from `version`. | -| [`version`](#version) | Numeric version encoded as `major * 100 + minor`. | - - - -### `is_lua51` (`boolean`) +| Field | Description | +| -------------- | ------------------------------------------------- | +| [`is_lua51`] | True only on Lua 5.1 runtimes. | +| [`is_lua52`] | True only on Lua 5.2 runtimes. | +| [`is_lua53`] | True only on Lua 5.3 runtimes. | +| [`is_lua54`] | True only on Lua 5.4 runtimes. | +| [`is_lua55`] | True only on Lua 5.5 runtimes. | +| [`is_luajit`] | True when running under LuaJIT. | +| [`is_windows`] | True when running on a Windows host. | +| [`major`] | Major version number parsed from `version`. | +| [`minor`] | Minor version number parsed from `version`. | +| [`version`] | Numeric version encoded as `major * 100 + minor`. | + +### `is_lua51` (`boolean`) {#is-lua51} True only on Lua 5.1 runtimes. @@ -40,9 +37,9 @@ True only on Lua 5.1 runtimes. print(runtime.is_lua51) --> true | false ``` - +--- -### `is_lua52` (`boolean`) +### `is_lua52` (`boolean`) {#is-lua52} True only on Lua 5.2 runtimes. @@ -50,9 +47,9 @@ True only on Lua 5.2 runtimes. print(runtime.is_lua52) --> true | false ``` - +--- -### `is_lua53` (`boolean`) +### `is_lua53` (`boolean`) {#is-lua53} True only on Lua 5.3 runtimes. @@ -60,9 +57,9 @@ True only on Lua 5.3 runtimes. print(runtime.is_lua53) --> true | false ``` - +--- -### `is_lua54` (`boolean`) +### `is_lua54` (`boolean`) {#is-lua54} True only on Lua 5.4 runtimes. @@ -70,9 +67,9 @@ True only on Lua 5.4 runtimes. print(runtime.is_lua54) --> true | false ``` - +--- -### `is_lua55` (`boolean`) +### `is_lua55` (`boolean`) {#is-lua55} True only on Lua 5.5 runtimes. @@ -80,9 +77,9 @@ True only on Lua 5.5 runtimes. print(runtime.is_lua55) --> true | false ``` - +--- -### `is_luajit` (`boolean`) +### `is_luajit` (`boolean`) {#is-luajit} True when running under LuaJIT. @@ -90,9 +87,9 @@ True when running under LuaJIT. print(runtime.is_luajit) --> true | false ``` - +--- -### `is_windows` (`boolean`) +### `is_windows` (`boolean`) {#is-windows} True when running on a Windows host. @@ -100,9 +97,9 @@ True when running on a Windows host. print(runtime.is_windows) --> true | false ``` - +--- -### `major` (`5`) +### `major` (`5`) {#major} Major version number parsed from `version`. @@ -110,9 +107,9 @@ Major version number parsed from `version`. print(runtime.major) --> 5 ``` - +--- -### `minor` (`1|2|3|4|5`) +### `minor` (`1` | `2` | `3` | `4` | `5`) {#minor} Minor version number parsed from `version`. @@ -120,12 +117,25 @@ Minor version number parsed from `version`. print(runtime.minor) --> 1 | 2 | 3 | 4 | 5 ``` - +--- -### `version` (`501|502|503|504|505`) +### `version` (`501` | `502` | `503` | `504` | `505`) {#version} Numeric version encoded as `major * 100 + minor`. ```lua print(runtime.version) --> 501 | 502 | 503 | 504 | 505 ``` + + +[`is_lua51`]: #is-lua51 +[`is_lua52`]: #is-lua52 +[`is_lua53`]: #is-lua53 +[`is_lua54`]: #is-lua54 +[`is_lua55`]: #is-lua55 +[`is_luajit`]: #is-luajit +[`is_windows`]: #is-windows +[`major`]: #major +[`minor`]: #minor +[`version`]: #version + diff --git a/docs/api/set.md b/docs/api/set.md index 84124f5..a60f195 100644 --- a/docs/api/set.md +++ b/docs/api/set.md @@ -1,15 +1,14 @@ --- +title: "set" description: "A set class for creating, combining, and querying unique values." --- -# `set` - A set class for creating, combining, and querying unique values. ## Usage ```lua -Set = require "mods.Set" +Set = mods.set s = Set({ "a" }) print(s:contains("a")) --> true @@ -19,74 +18,72 @@ print(s:contains("a")) --> true **Mutation**: -| Function | Description | -| --------------------------------------------------------------------- | ----------------------------------------------------------- | -| [`add(v)`](#fn-add) | Add an element to the set. | -| [`clear()`](#fn-clear) | Remove all elements from the set. | -| [`difference_update(set)`](#fn-difference-update) | Remove elements found in another set (in place). | -| [`intersection_update(set)`](#fn-intersection-update) | Keep only elements common to both sets (in place). | -| [`pop()`](#fn-pop) | Remove and return an arbitrary element. | -| [`symmetric_difference_update(set)`](#fn-symmetric-difference-update) | Update the set with elements not shared by both (in place). | -| [`update(set)`](#fn-update) | Add all elements from another set (in place). | +| Function | Description | +| ------------------------------------ | ----------------------------------------------------------- | +| [`add(v)`] | Add an element to the set. | +| [`clear()`] | Remove all elements from the set. | +| [`difference_update(set)`] | Remove elements found in another set (in place). | +| [`intersection_update(set)`] | Keep only elements common to both sets (in place). | +| [`pop()`] | Remove and return an arbitrary element. | +| [`symmetric_difference_update(set)`] | Update the set with elements not shared by both (in place). | +| [`update(set)`] | Add all elements from another set (in place). | **Predicates**: -| Function | Description | -| ----------------------------------- | ---------------------------------------------------------------- | -| [`equals(t)`](#fn-equals) | Return true when both sets contain exactly the same members. | -| [`isdisjoint(set)`](#fn-isdisjoint) | Return true if sets have no elements in common. | -| [`isempty()`](#fn-isempty) | Return true if the set has no elements. | -| [`issubset(t)`](#fn-issubset) | Return true if all elements of this set are also in another set. | -| [`issuperset(t)`](#fn-issuperset) | Return true if this set contains all elements of another set. | +| Function | Description | +| ------------------- | ---------------------------------------------------------------- | +| [`equals(t)`] | Return true when both sets contain exactly the same members. | +| [`isdisjoint(set)`] | Return true if sets have no elements in common. | +| [`isempty()`] | Return true if the set has no elements. | +| [`issubset(t)`] | Return true if all elements of this set are also in another set. | +| [`issuperset(t)`] | Return true if this set contains all elements of another set. | **Queries**: -| Function | Description | -| ----------------------------- | ----------------------------------------- | -| [`contains(v)`](#fn-contains) | Return true if the set contains `v`. | -| [`len()`](#fn-len) | Return the number of elements in the set. | +| Function | Description | +| --------------- | ----------------------------------------- | +| [`contains(v)`] | Return true if the set contains `v`. | +| [`len()`] | Return the number of elements in the set. | **Set Operations**: -| Function | Description | -| ----------------------------------------------------- | ---------------------------------------------------------------------------- | -| [`copy()`](#fn-copy) | Return a shallow copy of the set. | -| [`difference(t)`](#fn-difference) | Return elements in this set but not in another. | -| [`has(v)`](#fn-has) | Check whether a value is present in the set without following the metatable. | -| [`intersection(t)`](#fn-intersection) | Return elements common to both sets. | -| [`remove(v)`](#fn-remove) | Remove an element if present, do nothing otherwise. | -| [`symmetric_difference(t)`](#fn-symmetric-difference) | Return elements not shared by both sets. | -| [`union(t)`](#fn-union) | Return a new set with all elements from both. | +| Function | Description | +| --------------------------- | ---------------------------------------------------------------------------- | +| [`copy()`] | Return a shallow copy of the set. | +| [`difference(t)`] | Return elements in this set but not in another. | +| [`has(v)`] | Check whether a value is present in the set without following the metatable. | +| [`intersection(t)`] | Return elements common to both sets. | +| [`remove(v)`] | Remove an element if present, do nothing otherwise. | +| [`symmetric_difference(t)`] | Return elements not shared by both sets. | +| [`union(t)`] | Return a new set with all elements from both. | **Transforms**: -| Function | Description | -| --------------------------------- | ------------------------------------------------------- | -| [`join(sep?, quoted?)`](#fn-join) | Join set values into a string. | -| [`map(fn)`](#fn-map) | Return a new set by mapping each value. | -| [`mirror()`](#fn-mirror) | Mirror values into a new table as both keys and values. | -| [`tostring()`](#fn-tostring) | Render the set as a string. | -| [`values()`](#fn-values) | Return a list of all values in the set. | +| Function | Description | +| ----------------------- | ------------------------------------------------------- | +| [`join(sep?, quoted?)`] | Join set values into a string. | +| [`map(fn)`] | Return a new set by mapping each value. | +| [`mirror()`] | Mirror values into a new table as both keys and values. | +| [`tostring()`] | Render the set as a string. | +| [`values()`] | Return a list of all values in the set. | **Metamethods**: -| Function | Description | -| ------------------------------ | -------------------------------------------------------------------------- | -| [`__add(t)`](#fn-add) | Return the union of two sets using `+`. | -| [`__band(t)`](#fn-band) | Return the intersection of two sets using `&`. | -| [`__bor(t)`](#fn-bor) | Return the union of two sets using `\|`. | -| [`__bxor(t)`](#fn-bxor) | Return elements present in exactly one set using `^`. | -| [`__eq(t)`](#fn-eq) | Return true if both sets contain exactly the same members using `==`. | -| [`__le(t)`](#fn-le) | Return true if the left set is a subset of the right set using `<=`. | -| [`__lt(set)`](#fn-lt) | Return true if the left set is a proper subset of the right set using `<`. | -| [`__sub(set)`](#fn-sub) | Return the difference of two sets using `-`. | -| [`__tostring()`](#fn-tostring) | Render the set via `tostring(set)`. | +| Function | Description | +| ---------------- | -------------------------------------------------------------------------- | +| [`__add(t)`] | Return the union of two sets using `+`. | +| [`__band(t)`] | Return the intersection of two sets using `&`. | +| [`__bor(t)`] | Return the union of two sets using `\|`. | +| [`__bxor(t)`] | Return elements present in exactly one set using `^`. | +| [`__eq(t)`] | Return true if both sets contain exactly the same members using `==`. | +| [`__le(t)`] | Return true if the left set is a subset of the right set using `<=`. | +| [`__lt(set)`] | Return true if the left set is a proper subset of the right set using `<`. | +| [`__sub(set)`] | Return the difference of two sets using `-`. | +| [`__tostring()`] | Render the set via `tostring(set)`. | ### Mutation - - -#### `add(v)` +#### `add(v)` {#add} Add an element to the set. @@ -94,7 +91,7 @@ Add an element to the set. - `v` (`any`): Value to add. -**Return**: +**Returns**: - `self` (`T`): Current set. @@ -104,13 +101,13 @@ Add an element to the set. s = Set({ "a" }):add("b") --> s contains "a", "b" ``` - +--- -#### `clear()` +#### `clear()` {#clear} Remove all elements from the set. -**Return**: +**Returns**: - `self` (`T`): Current set. @@ -120,17 +117,17 @@ Remove all elements from the set. s = Set({ "a", "b" }):clear() --> s is empty ``` - +--- -#### `difference_update(set)` +#### `difference_update(set)` {#difference-update} Remove elements found in another set (in place). **Parameters**: -- `set` (`T|mods.List`): Other set/list. +- `set` (`T` | [`mods.List`]): Other set/list. -**Return**: +**Returns**: - `self` (`T`): Current set. @@ -140,17 +137,17 @@ Remove elements found in another set (in place). s = Set({ "a", "b" }):difference_update(Set({ "b" })) --> s contains "a" ``` - +--- -#### `intersection_update(set)` +#### `intersection_update(set)` {#intersection-update} Keep only elements common to both sets (in place). **Parameters**: -- `set` (`T|mods.List`): Other set/list. +- `set` (`T` | [`mods.List`]): Other set/list. -**Return**: +**Returns**: - `self` (`T`): Current set. @@ -161,13 +158,13 @@ s = Set({ "a", "b" }):intersection_update(Set({ "b", "c" })) --> s contains "b" ``` - +--- -#### `pop()` +#### `pop()` {#pop} Remove and return an arbitrary element. -**Return**: +**Returns**: - `removedValue` (`any`): Removed value, or `nil` when the set is empty. @@ -177,17 +174,17 @@ Remove and return an arbitrary element. v = Set({ "a", "b" }):pop() --> v is either "a" or "b" ``` - +--- -#### `symmetric_difference_update(set)` +#### `symmetric_difference_update(set)` {#symmetric-difference-update} Update the set with elements not shared by both (in place). **Parameters**: -- `set` (`T|mods.List`): Other set/list. +- `set` (`T` | [`mods.List`]): Other set/list. -**Return**: +**Returns**: - `self` (`T`): Current set. @@ -198,17 +195,17 @@ s = Set({ "a", "b" }):symmetric_difference_update(Set({ "b", "c" })) --> s contains "a", "c" ``` - +--- -#### `update(set)` +#### `update(set)` {#update} Add all elements from another set (in place). **Parameters**: -- `set` (`T|mods.List`): Other set/list. +- `set` (`T` | [`mods.List`]): Other set/list. -**Return**: +**Returns**: - `self` (`T`): Current set. @@ -218,19 +215,19 @@ Add all elements from another set (in place). s = Set({ "a" }):update(Set({ "b" })) --> s contains "a", "b" ``` -### Predicates +--- - +### Predicates -#### `equals(t)` +#### `equals(t)` {#equals} Return true when both sets contain exactly the same members. **Parameters**: -- `t` (`mods.Set|mods.List|table`): Other set/list. +- `t` ([`mods.Set`] | [`mods.List`] | `table`): Other set/list. -**Return**: +**Returns**: - `isEqual` (`boolean`): True when both sets contain the same members. @@ -247,17 +244,17 @@ ok = a:equals(b) --> true > `equals` is also available as the `__eq` (`==`) operator. `a:equals(b)` is > equivalent to `a == b`. - +--- -#### `isdisjoint(set)` +#### `isdisjoint(set)` {#isdisjoint} Return true if sets have no elements in common. **Parameters**: -- `set` (`T|mods.List`): Other set/list. +- `set` (`T` | [`mods.List`]): Other set/list. -**Return**: +**Returns**: - `isDisjoint` (`boolean`): True when sets have no elements in common. @@ -267,13 +264,13 @@ Return true if sets have no elements in common. ok = Set({ "a" }):isdisjoint(Set({ "b" })) --> true ``` - +--- -#### `isempty()` +#### `isempty()` {#isempty} Return true if the set has no elements. -**Return**: +**Returns**: - `isEmpty` (`boolean`): True when the set has no elements. @@ -283,17 +280,17 @@ Return true if the set has no elements. empty = Set({}):isempty() --> true ``` - +--- -#### `issubset(t)` +#### `issubset(t)` {#issubset} Return true if all elements of this set are also in another set. **Parameters**: -- `t` (`mods.Set|mods.List|table`): Other set/list. +- `t` ([`mods.Set`] | [`mods.List`] | `table`): Other set/list. -**Return**: +**Returns**: - `isSubset` (`boolean`): True when every element of `self` exists in `set`. @@ -308,17 +305,17 @@ ok = Set({ "a" }):issubset(Set({ "a", "b" })) --> true > `issubset` is also available as the `__le` (`<=`) operator. `a:issubset(b)` is > equivalent to `a <= b`. - +--- -#### `issuperset(t)` +#### `issuperset(t)` {#issuperset} Return true if this set contains all elements of another set. **Parameters**: -- `t` (`mods.Set|mods.List|table`): Other set/list. +- `t` ([`mods.Set`] | [`mods.List`] | `table`): Other set/list. -**Return**: +**Returns**: - `isSuperset` (`boolean`): True when `self` contains every element of `set`. @@ -328,11 +325,11 @@ Return true if this set contains all elements of another set. ok = Set({ "a", "b" }):issuperset(Set({ "a" })) --> true ``` -### Queries +--- - +### Queries -#### `contains(v)` +#### `contains(v)` {#contains} Return true if the set contains `v`. @@ -340,7 +337,7 @@ Return true if the set contains `v`. - `v` (`any`): Value to check. -**Return**: +**Returns**: - `isPresent` (`boolean`): True when `v` is present in the set. @@ -351,13 +348,13 @@ ok = Set({ "a", "b" }):contains("a") --> true ok = Set({ "a", "b" }):contains("z") --> false ``` - +--- -#### `len()` +#### `len()` {#len} Return the number of elements in the set. -**Return**: +**Returns**: - `count` (`integer`): Element count. @@ -367,17 +364,17 @@ Return the number of elements in the set. n = Set({ "a", "b" }):len() --> 2 ``` -### Set Operations +--- - +### Set Operations -#### `copy()` +#### `copy()` {#copy} Return a shallow copy of the set. -**Return**: +**Returns**: -- `set` (`mods.Set`): New set. +- `set` ([`mods.Set`]): New set. **Example**: @@ -385,19 +382,19 @@ Return a shallow copy of the set. c = Set({ "a" }):copy() --> c is a new set with "a" ``` - +--- -#### `difference(t)` +#### `difference(t)` {#difference} Return elements in this set but not in another. **Parameters**: -- `t` (`mods.Set|mods.List|table`): Other set/list. +- `t` ([`mods.Set`] | [`mods.List`] | `table`): Other set/list. -**Return**: +**Returns**: -- `set` (`mods.Set`): New set. +- `set` ([`mods.Set`]): New set. **Example**: @@ -410,9 +407,9 @@ d = Set({ "a", "b" }):difference(Set({ "b" })) --> d contains "a" > `difference` is also available as the `__sub` (`-`) operator. > `a:difference(b)` is equivalent to `a - b`. - +--- -#### `has(v)` +#### `has(v)` {#has} Check whether a value is present in the set without following the metatable. @@ -420,7 +417,7 @@ Check whether a value is present in the set without following the metatable. - `v` (`any`): Value to look up. -**Return**: +**Returns**: - `present` (`boolean`): Whether the value is present. @@ -432,19 +429,19 @@ print(s:has("a")) --> true print(s:has("__index")) --> false ``` - +--- -#### `intersection(t)` +#### `intersection(t)` {#intersection} Return elements common to both sets. **Parameters**: -- `t` (`mods.Set|mods.List|table`): Other set/list. +- `t` ([`mods.Set`] | [`mods.List`] | `table`): Other set/list. -**Return**: +**Returns**: -- `set` (`mods.Set`): New set. +- `set` ([`mods.Set`]): New set. **Example**: @@ -456,9 +453,9 @@ i = Set({ "a", "b" }):intersection(Set({ "b", "c" })) --> i contains "b" > > `intersection` is also available as `__band` (`&`) on Lua 5.3+. - +--- -#### `remove(v)` +#### `remove(v)` {#remove} Remove an element if present, do nothing otherwise. @@ -466,7 +463,7 @@ Remove an element if present, do nothing otherwise. - `v` (`any`): Value to remove. -**Return**: +**Returns**: - `self` (`T`): Current set. @@ -476,19 +473,19 @@ Remove an element if present, do nothing otherwise. s = Set({ "a", "b" }):remove("b") --> s contains "a" ``` - +--- -#### `symmetric_difference(t)` +#### `symmetric_difference(t)` {#symmetric-difference} Return elements not shared by both sets. **Parameters**: -- `t` (`mods.Set|mods.List|table`): Other set/list. +- `t` ([`mods.Set`] | [`mods.List`] | `table`): Other set/list. -**Return**: +**Returns**: -- `set` (`mods.Set`): New set. +- `set` ([`mods.Set`]): New set. **Example**: @@ -501,19 +498,19 @@ d = Set({ "a", "b" }):symmetric_difference(Set({ "b", "c" })) > > `symmetric_difference` is also available as `__bxor` (`^`) on Lua 5.3+. - +--- -#### `union(t)` +#### `union(t)` {#union} Return a new set with all elements from both. **Parameters**: -- `t` (`mods.Set|mods.List|table`): Other set/list. +- `t` ([`mods.Set`] | [`mods.List`] | `table`): Other set/list. -**Return**: +**Returns**: -- `set` (`mods.Set`): New set. +- `set` ([`mods.Set`]): New set. **Example**: @@ -526,11 +523,11 @@ s = Set({ "a" }):union(Set({ "b" })) --> s contains "a", "b" > `union` is available as `__add` (`+`) and `__bor` (`|`) on Lua 5.3+. > `a:union(b)` is equivalent to `a + b` and `a | b`. -### Transforms +--- - +### Transforms -#### `join(sep?, quoted?)` +#### `join(sep?, quoted?)` {#join} Join set values into a string. @@ -539,7 +536,7 @@ Join set values into a string. - `sep?` (`string`): Optional separator value (defaults to `""`). - `quoted?` (`boolean`): Optional boolean flag (defaults to `false`). -**Return**: +**Returns**: - `joined` (`string`): Joined string. @@ -554,9 +551,9 @@ s = Set({ "b", "a" }):join(", ", true) --> '"a", "b"' > > Join order is not guaranteed. - +--- -#### `map(fn)` +#### `map(fn)` {#map} Return a new set by mapping each value. @@ -564,9 +561,9 @@ Return a new set by mapping each value. - `fn` (`fun(v:any):any`): Mapping function. -**Return**: +**Returns**: -- `set` (`mods.Set`): New set. +- `set` ([`mods.Set`]): New set. **Example**: @@ -574,13 +571,13 @@ Return a new set by mapping each value. s = Set({ 1, 2 }):map(function(v) return v * 10 end) --> s contains 10, 20 ``` - +--- -#### `mirror()` +#### `mirror()` {#mirror} Mirror values into a new table as both keys and values. -**Return**: +**Returns**: - `mirroredValues` (`table`): Table mapping each value to itself. @@ -590,13 +587,13 @@ Mirror values into a new table as both keys and values. mirrored = Set({ "a", "b" }):mirror() --> { a = "a", b = "b" } ``` - +--- -#### `tostring()` +#### `tostring()` {#tostring} Render the set as a string. -**Return**: +**Returns**: - `renderedSet` (`string`): Rendered set string. @@ -606,15 +603,15 @@ Render the set as a string. s = Set({ "b", "a", 1 }):tostring() --> '{ 1, "a", "b" }' ``` - +--- -#### `values()` +#### `values()` {#values} Return a list of all values in the set. -**Return**: +**Returns**: -- `values` (`mods.List`): List of set values. +- `values` ([`mods.List`]): List of set values. **Example**: @@ -622,21 +619,21 @@ Return a list of all values in the set. values = Set({ "a", "b" }):values() --> { "a", "b" } ``` -### Metamethods +--- - +### Metamethods -#### `__add(t)` +#### `__add(t)` {#add-1} Return the union of two sets using `+`. **Parameters**: -- `t` (`mods.Set|mods.List|table`): Other set/list. +- `t` ([`mods.Set`] | [`mods.List`] | `table`): Other set/list. -**Return**: +**Returns**: -- `set` (`mods.Set`): New set. +- `set` ([`mods.Set`]): New set. **Example**: @@ -650,19 +647,19 @@ u = a + b --> { a = true, b = true, c = true } > > `__add` is the operator form of `:union(set)`. - +--- -#### `__band(t)` +#### `__band(t)` {#band} Return the intersection of two sets using `&`. **Parameters**: -- `t` (`mods.Set|mods.List|table`): Other set/list. +- `t` ([`mods.Set`] | [`mods.List`] | `table`): Other set/list. -**Return**: +**Returns**: -- `set` (`mods.Set`): New set. +- `set` ([`mods.Set`]): New set. **Example**: @@ -676,19 +673,19 @@ i = a & b --> { b = true } > > `__band` is the operator form of `:intersection(set)` on Lua 5.3+. - +--- -#### `__bor(t)` +#### `__bor(t)` {#bor} Return the union of two sets using `|`. **Parameters**: -- `t` (`mods.Set|mods.List|table`): Other set/list. +- `t` ([`mods.Set`] | [`mods.List`] | `table`): Other set/list. -**Return**: +**Returns**: -- `set` (`mods.Set`): New set. +- `set` ([`mods.Set`]): New set. **Example**: @@ -702,19 +699,19 @@ u = a | b --> { a = true, b = true, c = true } > > `__bor` is the operator form of `:union(set)` on Lua 5.3+. - +--- -#### `__bxor(t)` +#### `__bxor(t)` {#bxor} Return elements present in exactly one set using `^`. **Parameters**: -- `t` (`mods.Set|mods.List|table`): Other set/list. +- `t` ([`mods.Set`] | [`mods.List`] | `table`): Other set/list. -**Return**: +**Returns**: -- `set` (`mods.Set`): New set. +- `set` ([`mods.Set`]): New set. **Example**: @@ -728,17 +725,17 @@ d = a ^ b --> { a = true, c = true } > > `__bxor` is the operator form of `:symmetric_difference(set)` on Lua 5.3+. - +--- -#### `__eq(t)` +#### `__eq(t)` {#eq} Return true if both sets contain exactly the same members using `==`. **Parameters**: -- `t` (`mods.Set|mods.List|table`): Other set/list. +- `t` ([`mods.Set`] | [`mods.List`] | `table`): Other set/list. -**Return**: +**Returns**: - `isEqual` (`boolean`): True when both sets contain the same members. @@ -752,17 +749,17 @@ ok = Set({ "a", "b" }) == Set({ "b", "a" }) --> true > > `__eq` is the operator form of `:equals(set)`. - +--- -#### `__le(t)` +#### `__le(t)` {#le} Return true if the left set is a subset of the right set using `<=`. **Parameters**: -- `t` (`mods.Set|mods.List|table`): Other set/list. +- `t` ([`mods.Set`] | [`mods.List`] | `table`): Other set/list. -**Return**: +**Returns**: - `isSubset` (`boolean`): True when `self` is a subset of `set`. @@ -778,17 +775,17 @@ ok = a <= b --> true > > `__le` is the operator form of `:issubset(set)`. - +--- -#### `__lt(set)` +#### `__lt(set)` {#lt} Return true if the left set is a proper subset of the right set using `<`. **Parameters**: -- `set` (`mods.Set|table`): Other set. +- `set` ([`mods.Set`] | `table`): Other set. -**Return**: +**Returns**: - `isProperSubset` (`boolean`): True when `self` is a proper subset of `set`. @@ -800,19 +797,19 @@ b = Set({ "a", "b" }) ok = a < b --> true ``` - +--- -#### `__sub(set)` +#### `__sub(set)` {#sub} Return the difference of two sets using `-`. **Parameters**: -- `set` (`mods.Set|table`): Other set. +- `set` ([`mods.Set`] | `table`): Other set. -**Return**: +**Returns**: -- `set` (`mods.Set`): New set. +- `set` ([`mods.Set`]): New set. **Example**: @@ -826,13 +823,13 @@ d = a - b --> { a = true } > > `__sub` is the operator form of `:difference(set)`. - +--- -#### `__tostring()` +#### `__tostring()` {#tostring-1} Render the set via `tostring(set)`. -**Return**: +**Returns**: - `renderedSet` (`string`): Rendered set string. @@ -841,3 +838,43 @@ Render the set via `tostring(set)`. ```lua s = tostring(Set({ "b", "a", 1 })) --> '{ 1, "a", "b" }' ``` + + +[`__add(t)`]: #add-1 +[`__band(t)`]: #band +[`__bor(t)`]: #bor +[`__bxor(t)`]: #bxor +[`__eq(t)`]: #eq +[`__le(t)`]: #le +[`__lt(set)`]: #lt +[`__sub(set)`]: #sub +[`__tostring()`]: #tostring-1 +[`add(v)`]: #add +[`clear()`]: #clear +[`contains(v)`]: #contains +[`copy()`]: #copy +[`difference(t)`]: #difference +[`difference_update(set)`]: #difference-update +[`equals(t)`]: #equals +[`has(v)`]: #has +[`intersection(t)`]: #intersection +[`intersection_update(set)`]: #intersection-update +[`isdisjoint(set)`]: #isdisjoint +[`isempty()`]: #isempty +[`issubset(t)`]: #issubset +[`issuperset(t)`]: #issuperset +[`join(sep?, quoted?)`]: #join +[`len()`]: #len +[`map(fn)`]: #map +[`mirror()`]: #mirror +[`mods.List`]: /mods/api/list +[`mods.Set`]: /mods/api/set +[`pop()`]: #pop +[`remove(v)`]: #remove +[`symmetric_difference(t)`]: #symmetric-difference +[`symmetric_difference_update(set)`]: #symmetric-difference-update +[`tostring()`]: #tostring +[`union(t)`]: #union +[`update(set)`]: #update +[`values()`]: #values + diff --git a/docs/api/str.md b/docs/api/str.md index 7a5091e..e60698e 100644 --- a/docs/api/str.md +++ b/docs/api/str.md @@ -1,16 +1,15 @@ --- +title: "str" description: "String operations for searching, splitting, trimming, and formatting text." --- -# `str` - String operations for searching, splitting, trimming, and formatting text. ## Usage ```lua -str = require "mods.str" +str = mods.str print(str.capitalize("hello world")) --> "Hello world" ``` @@ -19,84 +18,82 @@ print(str.capitalize("hello world")) --> "Hello world" **Casing & Transform**: -| Function | Description | -| -------------------------------------------------------- | --------------------------------------------------------- | -| [`startswith(s, prefix, start?, stop?)`](#fn-startswith) | Return true if string starts with prefix. | -| [`swapcase(s)`](#fn-swapcase) | Return a copy with case of alphabetic characters swapped. | -| [`title(s)`](#fn-title) | Return titlecased copy. | -| [`translate(s, table_map)`](#fn-translate) | Translate characters using a mapping table. | -| [`upper(s)`](#fn-upper) | Return uppercased copy. | -| [`zfill(s, width)`](#fn-zfill) | Pad numeric string on the left with zeros. | +| Function | Description | +| ---------------------------------------- | --------------------------------------------------------- | +| [`startswith(s, prefix, start?, stop?)`] | Return true if string starts with prefix. | +| [`swapcase(s)`] | Return a copy with case of alphabetic characters swapped. | +| [`title(s)`] | Return titlecased copy. | +| [`translate(s, table_map)`] | Translate characters using a mapping table. | +| [`upper(s)`] | Return uppercased copy. | +| [`zfill(s, width)`] | Pad numeric string on the left with zeros. | **Formatting**: -| Function | Description | -| ---------------------------------------------------- | --------------------------------------------------------------------- | -| [`capitalize(s)`](#fn-capitalize) | Return copy with first character capitalized and the rest lowercased. | -| [`center(s, width, fillchar?)`](#fn-center) | Center string within width, padded with fill characters. | -| [`count(s, sub, start?, stop?)`](#fn-count) | Count non-overlapping occurrences of a substring. | -| [`endswith(s, suffix, start?, stop?)`](#fn-endswith) | Return true if string ends with suffix. | -| [`expandtabs(s, tabsize?)`](#fn-expandtabs) | Expand tabs to spaces using given tabsize. | -| [`find(s, sub, start?, stop?)`](#fn-find) | Return lowest index of substring or nil if not found. | -| [`format_map(s, mapping)`](#fn-format-map) | Format string with mapping (key-based) replacement. | +| Function | Description | +| -------------------------------------- | --------------------------------------------------------------------- | +| [`capitalize(s)`] | Return copy with first character capitalized and the rest lowercased. | +| [`center(s, width, fillchar?)`] | Center string within width, padded with fill characters. | +| [`count(s, sub, start?, stop?)`] | Count non-overlapping occurrences of a substring. | +| [`endswith(s, suffix, start?, stop?)`] | Return true if string ends with suffix. | +| [`expandtabs(s, tabsize?)`] | Expand tabs to spaces using given tabsize. | +| [`find(s, sub, start?, stop?)`] | Return lowest index of substring or nil if not found. | +| [`format_map(s, mapping)`] | Format string with mapping (key-based) replacement. | **Layout**: -| Function | Description | -| ----------------------------------------- | ------------------------------------------------------------------- | -| [`join(sep, ls)`](#fn-join) | Join an array-like table of strings using this string as separator. | -| [`ljust(s, width, fillchar?)`](#fn-ljust) | Left-justify string in a field of given width. | -| [`lower(s)`](#fn-lower) | Return lowercased copy. | -| [`lstrip(s, chars?)`](#fn-lstrip) | Remove leading characters (default: whitespace). | -| [`rstrip(s, chars?)`](#fn-rstrip) | Remove trailing characters (default: whitespace). | -| [`strip(s, chars?)`](#fn-strip) | Remove leading and trailing characters (default: whitespace). | +| Function | Description | +| ------------------------------ | ------------------------------------------------------------------- | +| [`join(sep, ls)`] | Join an array-like table of strings using this string as separator. | +| [`ljust(s, width, fillchar?)`] | Left-justify string in a field of given width. | +| [`lower(s)`] | Return lowercased copy. | +| [`lstrip(s, chars?)`] | Remove leading characters (default: whitespace). | +| [`rstrip(s, chars?)`] | Remove trailing characters (default: whitespace). | +| [`strip(s, chars?)`] | Remove leading and trailing characters (default: whitespace). | **Predicates**: -| Function | Description | -| ------------------------------------- | -------------------------------------------------------------------------------------------- | -| [`isalnum(s)`](#fn-isalnum) | Return true if all characters are alphanumeric and string is non-empty. | -| [`isalpha(s)`](#fn-isalpha) | Return true if all characters are alphabetic and string is non-empty. | -| [`isascii(s)`](#fn-isascii) | Return true if all characters are ASCII. | -| [`isdecimal(s)`](#fn-isdecimal) | Return true if all characters are decimal characters and string is non-empty. | -| [`isidentifier(s)`](#fn-isidentifier) | Return true if string is a valid identifier and not a reserved keyword. | -| [`islower(s)`](#fn-islower) | Return true if all cased characters are lowercase and there is at least one cased character. | -| [`isprintable(s)`](#fn-isprintable) | Return true if all characters are printable. | -| [`isspace(s)`](#fn-isspace) | Return true if all characters are whitespace and string is non-empty. | -| [`istitle(s)`](#fn-istitle) | Return true if string is titlecased. | -| [`isupper(s)`](#fn-isupper) | Return true if all cased characters are uppercase and there is at least one cased character. | +| Function | Description | +| ------------------- | -------------------------------------------------------------------------------------------- | +| [`isalnum(s)`] | Return true if all characters are alphanumeric and string is non-empty. | +| [`isalpha(s)`] | Return true if all characters are alphabetic and string is non-empty. | +| [`isascii(s)`] | Return true if all characters are ASCII. | +| [`isdecimal(s)`] | Return true if all characters are decimal characters and string is non-empty. | +| [`isidentifier(s)`] | Return true if string is a valid identifier and not a reserved keyword. | +| [`islower(s)`] | Return true if all cased characters are lowercase and there is at least one cased character. | +| [`isprintable(s)`] | Return true if all characters are printable. | +| [`isspace(s)`] | Return true if all characters are whitespace and string is non-empty. | +| [`istitle(s)`] | Return true if string is titlecased. | +| [`isupper(s)`] | Return true if all cased characters are uppercase and there is at least one cased character. | **Split & Replace**: -| Function | Description | -| --------------------------------------------- | ------------------------------------------------------------------------- | -| [`partition(s, sep)`](#fn-partition) | Partition string into head, sep, tail from left. | -| [`removeprefix(s, prefix)`](#fn-removeprefix) | Remove prefix if present. | -| [`removesuffix(s, suffix)`](#fn-removesuffix) | Remove suffix if present. | -| [`replace(s, old, new, count?)`](#fn-replace) | Return a copy of the string with all occurrences of a substring replaced. | -| [`rfind(s, sub, start?, stop?)`](#fn-rfind) | Return highest index of substring or nil if not found. | -| [`rjust(s, width, fillchar?)`](#fn-rjust) | Right-justify string in a field of given width. | -| [`rpartition(s, sep)`](#fn-rpartition) | Partition string into head, sep, tail from right. | -| [`rsplit(s, sep?, maxsplit?)`](#fn-rsplit) | Split from the right by separator, up to maxsplit. | -| [`split(s, sep?, maxsplit?)`](#fn-split) | Split by separator (or whitespace) up to maxsplit. | -| [`splitlines(s, keepends?)`](#fn-splitlines) | Split on line boundaries. | +| Function | Description | +| -------------------------------- | ------------------------------------------------------------------------- | +| [`partition(s, sep)`] | Partition string into head, sep, tail from left. | +| [`removeprefix(s, prefix)`] | Remove prefix if present. | +| [`removesuffix(s, suffix)`] | Remove suffix if present. | +| [`replace(s, old, new, count?)`] | Return a copy of the string with all occurrences of a substring replaced. | +| [`rfind(s, sub, start?, stop?)`] | Return highest index of substring or nil if not found. | +| [`rjust(s, width, fillchar?)`] | Right-justify string in a field of given width. | +| [`rpartition(s, sep)`] | Partition string into head, sep, tail from right. | +| [`rsplit(s, sep?, maxsplit?)`] | Split from the right by separator, up to maxsplit. | +| [`split(s, sep?, maxsplit?)`] | Split by separator (or whitespace) up to maxsplit. | +| [`splitlines(s, keepends?)`] | Split on line boundaries. | ### Casing & Transform - - -#### `startswith(s, prefix, start?, stop?)` +#### `startswith(s, prefix, start?, stop?)` {#startswith} Return true if string starts with prefix. **Parameters**: - `s` (`string`): Input string. -- `prefix` (`string|string[]`): Prefix string. +- `prefix` (`string` | `string[]`): Prefix string. - `start?` (`integer`): Optional start index (defaults to `1`). - `stop?` (`integer`): Optional exclusive end index (defaults to `#s + 1`). -**Return**: +**Returns**: - `hasPrefix` (`boolean`): True when `s` starts with `prefix`. @@ -110,9 +107,9 @@ ok = startswith("hello.lua", "he") --> true > > If prefix is a list, returns `true` when any prefix matches. - +--- -#### `swapcase(s)` +#### `swapcase(s)` {#swapcase} Return a copy with case of alphabetic characters swapped. @@ -120,7 +117,7 @@ Return a copy with case of alphabetic characters swapped. - `s` (`string`): Input string. -**Return**: +**Returns**: - `swappedCase` (`string`): String with alphabetic case swapped. @@ -130,9 +127,9 @@ Return a copy with case of alphabetic characters swapped. s = swapcase("AbC") --> "aBc" ``` - +--- -#### `title(s)` +#### `title(s)` {#title} Return titlecased copy. @@ -140,7 +137,7 @@ Return titlecased copy. - `s` (`string`): Input string. -**Return**: +**Returns**: - `titlecased` (`string`): Titlecased string. @@ -150,9 +147,9 @@ Return titlecased copy. s = title("hello world") --> "Hello World" ``` - +--- -#### `translate(s, table_map)` +#### `translate(s, table_map)` {#translate} Translate characters using a mapping table. @@ -161,7 +158,7 @@ Translate characters using a mapping table. - `s` (`string`): Input string. - `table_map` (`table`): Character translation map. -**Return**: +**Returns**: - `translated` (`string`): Translated string. @@ -172,9 +169,9 @@ map = { [string.byte("a")] = "b", ["c"] = false } s = translate("abc", map) --> "bb" ``` - +--- -#### `upper(s)` +#### `upper(s)` {#upper} Return uppercased copy. @@ -182,7 +179,7 @@ Return uppercased copy. - `s` (`string`): Input string. -**Return**: +**Returns**: - `uppercased` (`string`): Uppercased string. @@ -192,9 +189,9 @@ Return uppercased copy. s = upper("Hello") --> "HELLO" ``` - +--- -#### `zfill(s, width)` +#### `zfill(s, width)` {#zfill} Pad numeric string on the left with zeros. @@ -203,7 +200,7 @@ Pad numeric string on the left with zeros. - `s` (`string`): Input string. - `width` (`integer`): Target width. -**Return**: +**Returns**: - `zeroFilled` (`string`): Zero-padded string. @@ -213,11 +210,11 @@ Pad numeric string on the left with zeros. s = zfill("42", 5) --> "00042" ``` -### Formatting +--- - +### Formatting -#### `capitalize(s)` +#### `capitalize(s)` {#capitalize} Return copy with first character capitalized and the rest lowercased. @@ -225,7 +222,7 @@ Return copy with first character capitalized and the rest lowercased. - `s` (`string`): Input string. -**Return**: +**Returns**: - `capitalized` (`string`): Capitalized string. @@ -235,9 +232,9 @@ Return copy with first character capitalized and the rest lowercased. s = capitalize("hello WORLD") --> "Hello world" ``` - +--- -#### `center(s, width, fillchar?)` +#### `center(s, width, fillchar?)` {#center} Center string within width, padded with fill characters. @@ -247,7 +244,7 @@ Center string within width, padded with fill characters. - `width` (`integer`): Target width. - `fillchar?` (`string`): Optional fill character. -**Return**: +**Returns**: - `centered` (`string`): Centered string. @@ -257,9 +254,9 @@ Center string within width, padded with fill characters. s = center("hi", 6, "-") --> "--hi--" ``` - +--- -#### `count(s, sub, start?, stop?)` +#### `count(s, sub, start?, stop?)` {#count} Count non-overlapping occurrences of a substring. @@ -270,7 +267,7 @@ Count non-overlapping occurrences of a substring. - `start?` (`integer`): Optional start index (defaults to `1`). - `stop?` (`integer`): Optional exclusive end index (defaults to `#s + 1`). -**Return**: +**Returns**: - `count` (`integer`): Number of non-overlapping matches. @@ -282,20 +279,20 @@ n = count("aaaa", "a", 2, -1) --> 2 n = count("abcd", "") --> 5 ``` - +--- -#### `endswith(s, suffix, start?, stop?)` +#### `endswith(s, suffix, start?, stop?)` {#endswith} Return true if string ends with suffix. **Parameters**: - `s` (`string`): Input string. -- `suffix` (`string|string[]`): Suffix string. +- `suffix` (`string` | `string[]`): Suffix string. - `start?` (`integer`): Optional start index (defaults to `1`). - `stop?` (`integer`): Optional exclusive end index (defaults to `#s + 1`). -**Return**: +**Returns**: - `hasSuffix` (`boolean`): True when `s` ends with `suffix`. @@ -309,9 +306,9 @@ ok = endswith("hello.lua", ".lua") --> true > > If suffix is a list, returns `true` when any suffix matches. - +--- -#### `expandtabs(s, tabsize?)` +#### `expandtabs(s, tabsize?)` {#expandtabs} Expand tabs to spaces using given tabsize. @@ -320,7 +317,7 @@ Expand tabs to spaces using given tabsize. - `s` (`string`): Input string. - `tabsize?` (`integer`): Optional tab width (defaults to `8`). -**Return**: +**Returns**: - `expanded` (`string`): String with tabs expanded. @@ -330,9 +327,9 @@ Expand tabs to spaces using given tabsize. s = expandtabs("a\tb", 4) --> "a b" ``` - +--- -#### `find(s, sub, start?, stop?)` +#### `find(s, sub, start?, stop?)` {#find} Return lowest index of substring or nil if not found. @@ -343,9 +340,9 @@ Return lowest index of substring or nil if not found. - `start?` (`integer`): Optional start index (defaults to `1`). - `stop?` (`integer`): Optional exclusive end index (defaults to `#s + 1`). -**Return**: +**Returns**: -- `index` (`integer?`): First match index, or `nil` when not found. +- `index?` (`integer`): First match index, or `nil` when not found. **Example**: @@ -353,9 +350,9 @@ Return lowest index of substring or nil if not found. i = find("hello", "ll") --> 3 ``` - +--- -#### `format_map(s, mapping)` +#### `format_map(s, mapping)` {#format-map} Format string with mapping (key-based) replacement. @@ -364,7 +361,7 @@ Format string with mapping (key-based) replacement. - `s` (`string`): Template string with `{key}` placeholders. - `mapping` (`table`): Values used to replace placeholder keys. -**Return**: +**Returns**: - `formatted` (`string`): Formatted string with placeholders replaced. @@ -377,13 +374,13 @@ s = format_map("hi {name}", { name = "bob" }) --> "hi bob" > [!NOTE] > > `format_map` is a lightweight `{key}` replacement helper. For richer -> templating, use `mods.template`. +> templating, use [`mods.template`]. -### Layout +--- - +### Layout -#### `join(sep, ls)` +#### `join(sep, ls)` {#join} Join an array-like table of strings using this string as separator. @@ -392,7 +389,7 @@ Join an array-like table of strings using this string as separator. - `sep` (`string`): Separator value. - `ls` (`string[]`): Table value. -**Return**: +**Returns**: - `joined` (`string`): Joined string. @@ -402,9 +399,9 @@ Join an array-like table of strings using this string as separator. s = join(",", { "a", "b", "c" }) --> "a,b,c" ``` - +--- -#### `ljust(s, width, fillchar?)` +#### `ljust(s, width, fillchar?)` {#ljust} Left-justify string in a field of given width. @@ -414,7 +411,7 @@ Left-justify string in a field of given width. - `width` (`integer`): Target width. - `fillchar?` (`string`): Optional fill character. -**Return**: +**Returns**: - `leftJustified` (`string`): Left-justified string. @@ -424,9 +421,9 @@ Left-justify string in a field of given width. s = ljust("hi", 5, ".") --> "hi..." ``` - +--- -#### `lower(s)` +#### `lower(s)` {#lower} Return lowercased copy. @@ -434,7 +431,7 @@ Return lowercased copy. - `s` (`string`): Input string. -**Return**: +**Returns**: - `lowercased` (`string`): Lowercased string. @@ -444,9 +441,9 @@ Return lowercased copy. s = lower("HeLLo") --> "hello" ``` - +--- -#### `lstrip(s, chars?)` +#### `lstrip(s, chars?)` {#lstrip} Remove leading characters (default: whitespace). @@ -455,7 +452,7 @@ Remove leading characters (default: whitespace). - `s` (`string`): Input string. - `chars?` (`string`): Optional character set. -**Return**: +**Returns**: - `leadingStripped` (`string`): String with leading characters removed. @@ -465,9 +462,9 @@ Remove leading characters (default: whitespace). s = lstrip(" hello") --> "hello" ``` - +--- -#### `rstrip(s, chars?)` +#### `rstrip(s, chars?)` {#rstrip} Remove trailing characters (default: whitespace). @@ -476,7 +473,7 @@ Remove trailing characters (default: whitespace). - `s` (`string`): Input string. - `chars?` (`string`): Optional character set. -**Return**: +**Returns**: - `trailingStripped` (`string`): String with trailing characters removed. @@ -486,9 +483,9 @@ Remove trailing characters (default: whitespace). s = rstrip("hello ") --> "hello" ``` - +--- -#### `strip(s, chars?)` +#### `strip(s, chars?)` {#strip} Remove leading and trailing characters (default: whitespace). @@ -497,7 +494,7 @@ Remove leading and trailing characters (default: whitespace). - `s` (`string`): Input string. - `chars?` (`string`): Optional character set. -**Return**: +**Returns**: - `stripped` (`string`): String with leading and trailing characters removed. @@ -507,11 +504,11 @@ Remove leading and trailing characters (default: whitespace). s = strip(" hello ") --> "hello" ``` -### Predicates +--- - +### Predicates -#### `isalnum(s)` +#### `isalnum(s)` {#isalnum} Return true if all characters are alphanumeric and string is non-empty. @@ -519,7 +516,7 @@ Return true if all characters are alphanumeric and string is non-empty. - `s` (`string`): Input string. -**Return**: +**Returns**: - `isAlnum` (`boolean`): True when `s` is non-empty and all characters are alphanumeric. @@ -538,9 +535,9 @@ ok = isalnum("abc123") --> true > isalnum("á1") --> false > ``` - +--- -#### `isalpha(s)` +#### `isalpha(s)` {#isalpha} Return true if all characters are alphabetic and string is non-empty. @@ -548,7 +545,7 @@ Return true if all characters are alphabetic and string is non-empty. - `s` (`string`): Input string. -**Return**: +**Returns**: - `isAlpha` (`boolean`): True when `s` is non-empty and all characters are alphabetic. @@ -567,9 +564,9 @@ ok = isalpha("abc") --> true > isalpha("á") --> false > ``` - +--- -#### `isascii(s)` +#### `isascii(s)` {#isascii} Return true if all characters are ASCII. @@ -577,7 +574,7 @@ Return true if all characters are ASCII. - `s` (`string`): Input string. -**Return**: +**Returns**: - `isAscii` (`boolean`): True when all bytes in `s` are ASCII. @@ -591,9 +588,9 @@ ok = isascii("hello") --> true > > The empty string returns `true`. - +--- -#### `isdecimal(s)` +#### `isdecimal(s)` {#isdecimal} Return true if all characters are decimal characters and string is non-empty. @@ -601,7 +598,7 @@ Return true if all characters are decimal characters and string is non-empty. - `s` (`string`): Input string. -**Return**: +**Returns**: - `isDecimal` (`boolean`): True when `s` is non-empty and all characters are decimal digits. @@ -612,9 +609,9 @@ Return true if all characters are decimal characters and string is non-empty. ok = isdecimal("123") --> true ``` - +--- -#### `isidentifier(s)` +#### `isidentifier(s)` {#isidentifier} Return true if string is a valid identifier and not a reserved keyword. @@ -622,7 +619,7 @@ Return true if string is a valid identifier and not a reserved keyword. - `s` (`string`): Input string. -**Return**: +**Returns**: - `isIdentifier` (`boolean`): True when `s` is a valid identifier and not a keyword. @@ -635,9 +632,9 @@ ok = isidentifier("2var") --> false ok = isidentifier("end") --> false (keyword) ``` - +--- -#### `islower(s)` +#### `islower(s)` {#islower} Return true if all cased characters are lowercase and there is at least one cased character. @@ -646,7 +643,7 @@ cased character. - `s` (`string`): Input string. -**Return**: +**Returns**: - `isLower` (`boolean`): True when `s` has at least one cased character and all are lowercase. @@ -657,9 +654,9 @@ cased character. ok = islower("hello") --> true ``` - +--- -#### `isprintable(s)` +#### `isprintable(s)` {#isprintable} Return true if all characters are printable. @@ -667,7 +664,7 @@ Return true if all characters are printable. - `s` (`string`): Input string. -**Return**: +**Returns**: - `isPrintable` (`boolean`): True when all bytes in `s` are printable ASCII. @@ -681,9 +678,9 @@ ok = isprintable("abc!") --> true > > The empty string returns `true`. - +--- -#### `isspace(s)` +#### `isspace(s)` {#isspace} Return true if all characters are whitespace and string is non-empty. @@ -691,7 +688,7 @@ Return true if all characters are whitespace and string is non-empty. - `s` (`string`): Input string. -**Return**: +**Returns**: - `isSpace` (`boolean`): True when `s` is non-empty and all characters are whitespace. @@ -702,9 +699,9 @@ Return true if all characters are whitespace and string is non-empty. ok = isspace(" \t") --> true ``` - +--- -#### `istitle(s)` +#### `istitle(s)` {#istitle} Return true if string is titlecased. @@ -712,7 +709,7 @@ Return true if string is titlecased. - `s` (`string`): Input string. -**Return**: +**Returns**: - `isTitle` (`boolean`): True when `s` is titlecased. @@ -722,9 +719,9 @@ Return true if string is titlecased. ok = istitle("Hello World") --> true ``` - +--- -#### `isupper(s)` +#### `isupper(s)` {#isupper} Return true if all cased characters are uppercase and there is at least one cased character. @@ -733,7 +730,7 @@ cased character. - `s` (`string`): Input string. -**Return**: +**Returns**: - `isUpper` (`boolean`): True when `s` has at least one cased character and all are uppercase. @@ -744,11 +741,11 @@ cased character. ok = isupper("HELLO") --> true ``` -### Split & Replace +--- - +### Split & Replace -#### `partition(s, sep)` +#### `partition(s, sep)` {#partition} Partition string into head, sep, tail from left. @@ -757,7 +754,7 @@ Partition string into head, sep, tail from left. - `s` (`string`): Input string. - `sep` (`string`): Separator value. -**Return**: +**Returns**: - `head` (`string`): Part before the separator. - `separator` (`string`): Matched separator, or empty string when not found. @@ -769,9 +766,9 @@ Partition string into head, sep, tail from left. a, b, c = partition("a-b-c", "-") --> "a", "-", "b-c" ``` - +--- -#### `removeprefix(s, prefix)` +#### `removeprefix(s, prefix)` {#removeprefix} Remove prefix if present. @@ -780,7 +777,7 @@ Remove prefix if present. - `s` (`string`): Input string. - `prefix` (`string`): Prefix string. -**Return**: +**Returns**: - `prefixRemoved` (`string`): String with prefix removed when present. @@ -790,9 +787,9 @@ Remove prefix if present. s = removeprefix("foobar", "foo") --> "bar" ``` - +--- -#### `removesuffix(s, suffix)` +#### `removesuffix(s, suffix)` {#removesuffix} Remove suffix if present. @@ -801,7 +798,7 @@ Remove suffix if present. - `s` (`string`): Input string. - `suffix` (`string`): Suffix string. -**Return**: +**Returns**: - `suffixRemoved` (`string`): String with suffix removed when present. @@ -811,9 +808,9 @@ Remove suffix if present. s = removesuffix("foobar", "bar") --> "foo" ``` - +--- -#### `replace(s, old, new, count?)` +#### `replace(s, old, new, count?)` {#replace} Return a copy of the string with all occurrences of a substring replaced. @@ -824,7 +821,7 @@ Return a copy of the string with all occurrences of a substring replaced. - `new` (`string`): Replacement string. - `count?` (`integer`): Optional maximum replacement count. -**Return**: +**Returns**: - `replaced` (`string`): String with replacements applied. @@ -834,9 +831,9 @@ Return a copy of the string with all occurrences of a substring replaced. s = replace("a-b-c", "-", "_", 1) --> "a_b-c" ``` - +--- -#### `rfind(s, sub, start?, stop?)` +#### `rfind(s, sub, start?, stop?)` {#rfind} Return highest index of substring or nil if not found. @@ -847,9 +844,9 @@ Return highest index of substring or nil if not found. - `start?` (`integer`): Optional start index (defaults to `1`). - `stop?` (`integer`): Optional inclusive end index (defaults to `#s`). -**Return**: +**Returns**: -- `index` (`integer?`): Last match index, or `nil` when not found. +- `index?` (`integer`): Last match index, or `nil` when not found. **Example**: @@ -857,9 +854,9 @@ Return highest index of substring or nil if not found. i = rfind("ababa", "ba") --> 4 ``` - +--- -#### `rjust(s, width, fillchar?)` +#### `rjust(s, width, fillchar?)` {#rjust} Right-justify string in a field of given width. @@ -869,7 +866,7 @@ Right-justify string in a field of given width. - `width` (`integer`): Target width. - `fillchar?` (`string`): Optional fill character. -**Return**: +**Returns**: - `rightJustified` (`string`): Right-justified string. @@ -879,9 +876,9 @@ Right-justify string in a field of given width. s = rjust("hi", 5, ".") --> "...hi" ``` - +--- -#### `rpartition(s, sep)` +#### `rpartition(s, sep)` {#rpartition} Partition string into head, sep, tail from right. @@ -890,7 +887,7 @@ Partition string into head, sep, tail from right. - `s` (`string`): Input string. - `sep` (`string`): Separator value. -**Return**: +**Returns**: - `head` (`string`): Part before the separator. - `separator` (`string`): Matched separator, or empty string when not found. @@ -902,9 +899,9 @@ Partition string into head, sep, tail from right. a, b, c = rpartition("a-b-c", "-") --> "a-b", "-", "c" ``` - +--- -#### `rsplit(s, sep?, maxsplit?)` +#### `rsplit(s, sep?, maxsplit?)` {#rsplit} Split from the right by separator, up to maxsplit. @@ -914,9 +911,9 @@ Split from the right by separator, up to maxsplit. - `sep?` (`string`): Optional separator value. - `maxsplit?` (`integer`): Optional maximum number of splits. -**Return**: +**Returns**: -- `parts` (`mods.List`): Split parts. +- `parts` ([`mods.List`]): Split parts. **Example**: @@ -924,9 +921,9 @@ Split from the right by separator, up to maxsplit. parts = rsplit("a,b,c", ",", 1) --> { "a,b", "c" } ``` - +--- -#### `split(s, sep?, maxsplit?)` +#### `split(s, sep?, maxsplit?)` {#split} Split by separator (or whitespace) up to maxsplit. @@ -936,9 +933,9 @@ Split by separator (or whitespace) up to maxsplit. - `sep?` (`string`): Optional separator value. - `maxsplit?` (`integer`): Optional maximum number of splits. -**Return**: +**Returns**: -- `parts` (`mods.List`): Split parts. +- `parts` ([`mods.List`]): Split parts. **Example**: @@ -946,9 +943,9 @@ Split by separator (or whitespace) up to maxsplit. parts = split("a,b,c", ",") --> { "a", "b", "c" } ``` - +--- -#### `splitlines(s, keepends?)` +#### `splitlines(s, keepends?)` {#splitlines} Split on line boundaries. @@ -957,12 +954,56 @@ Split on line boundaries. - `s` (`string`): Input string. - `keepends?` (`boolean`): Optional whether to keep line endings. -**Return**: +**Returns**: -- `lines` (`mods.List`): Split lines. +- `lines` ([`mods.List`]): Split lines. **Example**: ```lua lines = splitlines("a\nb\r\nc") --> { "a", "b", "c" } ``` + + +[`capitalize(s)`]: #capitalize +[`center(s, width, fillchar?)`]: #center +[`count(s, sub, start?, stop?)`]: #count +[`endswith(s, suffix, start?, stop?)`]: #endswith +[`expandtabs(s, tabsize?)`]: #expandtabs +[`find(s, sub, start?, stop?)`]: #find +[`format_map(s, mapping)`]: #format-map +[`isalnum(s)`]: #isalnum +[`isalpha(s)`]: #isalpha +[`isascii(s)`]: #isascii +[`isdecimal(s)`]: #isdecimal +[`isidentifier(s)`]: #isidentifier +[`islower(s)`]: #islower +[`isprintable(s)`]: #isprintable +[`isspace(s)`]: #isspace +[`istitle(s)`]: #istitle +[`isupper(s)`]: #isupper +[`join(sep, ls)`]: #join +[`ljust(s, width, fillchar?)`]: #ljust +[`lower(s)`]: #lower +[`lstrip(s, chars?)`]: #lstrip +[`mods.List`]: /mods/api/list +[`mods.template`]: /mods/api/template +[`partition(s, sep)`]: #partition +[`removeprefix(s, prefix)`]: #removeprefix +[`removesuffix(s, suffix)`]: #removesuffix +[`replace(s, old, new, count?)`]: #replace +[`rfind(s, sub, start?, stop?)`]: #rfind +[`rjust(s, width, fillchar?)`]: #rjust +[`rpartition(s, sep)`]: #rpartition +[`rsplit(s, sep?, maxsplit?)`]: #rsplit +[`rstrip(s, chars?)`]: #rstrip +[`split(s, sep?, maxsplit?)`]: #split +[`splitlines(s, keepends?)`]: #splitlines +[`startswith(s, prefix, start?, stop?)`]: #startswith +[`strip(s, chars?)`]: #strip +[`swapcase(s)`]: #swapcase +[`title(s)`]: #title +[`translate(s, table_map)`]: #translate +[`upper(s)`]: #upper +[`zfill(s, width)`]: #zfill + diff --git a/docs/api/stringcase.md b/docs/api/stringcase.md index 977d9c8..02c763a 100644 --- a/docs/api/stringcase.md +++ b/docs/api/stringcase.md @@ -1,15 +1,14 @@ --- +title: "stringcase" description: "String case conversion and word splitting." --- -# `stringcase` - String case conversion and word splitting. ## Usage ```lua -stringcase = require "mods.stringcase" +stringcase = mods.stringcase print(stringcase.snake("FooBar")) --> "foo_bar" ``` @@ -18,40 +17,38 @@ print(stringcase.snake("FooBar")) --> "foo_bar" **Basic**: -| Function | Description | -| ----------------------- | -------------------------------- | -| [`lower(s)`](#fn-lower) | Convert string to all lowercase. | -| [`upper(s)`](#fn-upper) | Convert string to all uppercase. | +| Function | Description | +| ------------ | -------------------------------- | +| [`lower(s)`] | Convert string to all lowercase. | +| [`upper(s)`] | Convert string to all uppercase. | **Letter Case**: -| Function | Description | -| --------------------------------- | ------------------------------------------------------------------------- | -| [`capitalize(s)`](#fn-capitalize) | Capitalize the first letter and lowercase the rest. | -| [`sentence(s)`](#fn-sentence) | Convert string to sentence case (first letter uppercase, rest unchanged). | -| [`swapcase(s)`](#fn-swapcase) | Swap case of each letter. | +| Function | Description | +| ----------------- | ------------------------------------------------------------------------- | +| [`capitalize(s)`] | Capitalize the first letter and lowercase the rest. | +| [`sentence(s)`] | Convert string to sentence case (first letter uppercase, rest unchanged). | +| [`swapcase(s)`] | Swap case of each letter. | **Word Case**: -| Function | Description | -| --------------------------------- | --------------------------------------------------------------------- | -| [`acronym(s)`](#fn-acronym) | Get acronym of words in string (first letters only). | -| [`camel(s)`](#fn-camel) | Convert string to camelCase. | -| [`constant(s)`](#fn-constant) | Convert string to CONSTANT_CASE (uppercase snake_case). | -| [`delimit(s, sep?)`](#fn-delimit) | Normalize to snake_case, then delimit words with a separator. | -| [`dot(s)`](#fn-dot) | Convert string to dot.case. | -| [`kebab(s)`](#fn-kebab) | Convert string to kebab-case. | -| [`pascal(s)`](#fn-pascal) | Convert string to PascalCase. | -| [`path(s)`](#fn-path) | Convert string to path/case (slashes between words). | -| [`snake(s)`](#fn-snake) | Convert string to snake_case. | -| [`space(s)`](#fn-space) | Convert string to space case (spaces between words). | -| [`title(s)`](#fn-title) | Convert string to Title Case (first letter of each word capitalized). | +| Function | Description | +| -------------------- | --------------------------------------------------------------------- | +| [`acronym(s)`] | Get acronym of words in string (first letters only). | +| [`camel(s)`] | Convert string to camelCase. | +| [`constant(s)`] | Convert string to CONSTANT_CASE (uppercase snake_case). | +| [`delimit(s, sep?)`] | Normalize to snake_case, then delimit words with a separator. | +| [`dot(s)`] | Convert string to dot.case. | +| [`kebab(s)`] | Convert string to kebab-case. | +| [`pascal(s)`] | Convert string to PascalCase. | +| [`path(s)`] | Convert string to path/case (slashes between words). | +| [`snake(s)`] | Convert string to snake_case. | +| [`space(s)`] | Convert string to space case (spaces between words). | +| [`title(s)`] | Convert string to Title Case (first letter of each word capitalized). | ### Basic - - -#### `lower(s)` +#### `lower(s)` {#lower} Convert string to all lowercase. @@ -59,7 +56,7 @@ Convert string to all lowercase. - `s` (`string`): Input string. -**Return**: +**Returns**: - `lowercased` (`string`): Lowercased string. @@ -70,9 +67,9 @@ lower("foo_bar-baz") --> "foo_bar-baz" lower("FooBar baz") --> "foobar baz" ``` - +--- -#### `upper(s)` +#### `upper(s)` {#upper} Convert string to all uppercase. @@ -80,7 +77,7 @@ Convert string to all uppercase. - `s` (`string`): Input string. -**Return**: +**Returns**: - `uppercased` (`string`): Uppercased string. @@ -91,11 +88,11 @@ upper("foo_bar-baz") --> "FOO_BAR-BAZ" upper("FooBar baz") --> "FOOBAR BAZ" ``` -### Letter Case +--- - +### Letter Case -#### `capitalize(s)` +#### `capitalize(s)` {#capitalize} Capitalize the first letter and lowercase the rest. @@ -103,7 +100,7 @@ Capitalize the first letter and lowercase the rest. - `s` (`string`): Input string. -**Return**: +**Returns**: - `capitalized` (`string`): Capitalized string. @@ -114,9 +111,9 @@ capitalize("foo_bar-baz") --> "Foo_bar-baz" capitalize("FooBar baz") --> "Foobar baz" ``` - +--- -#### `sentence(s)` +#### `sentence(s)` {#sentence} Convert string to sentence case (first letter uppercase, rest unchanged). @@ -124,7 +121,7 @@ Convert string to sentence case (first letter uppercase, rest unchanged). - `s` (`string`): Input string. -**Return**: +**Returns**: - `sentenceCased` (`string`): Sentence-cased string. @@ -135,9 +132,9 @@ sentence("foo_bar-baz") --> "Foo_bar-baz" sentence("FooBar baz") --> "FooBar baz" ``` - +--- -#### `swapcase(s)` +#### `swapcase(s)` {#swapcase} Swap case of each letter. @@ -145,7 +142,7 @@ Swap case of each letter. - `s` (`string`): Input string. -**Return**: +**Returns**: - `swapCased` (`string`): Swap-cased string. @@ -156,11 +153,11 @@ swapcase("foo_bar-baz") --> "FOO_BAR-BAZ" swapcase("FooBar baz") --> "fOObAR BAZ" ``` -### Word Case +--- - +### Word Case -#### `acronym(s)` +#### `acronym(s)` {#acronym} Get acronym of words in string (first letters only). @@ -168,7 +165,7 @@ Get acronym of words in string (first letters only). - `s` (`string`): Input string. -**Return**: +**Returns**: - `acronym` (`string`): Acronym string. @@ -179,9 +176,9 @@ acronym("foo_bar-baz") --> "FBB" acronym("FooBar baz") --> "FBB" ``` - +--- -#### `camel(s)` +#### `camel(s)` {#camel} Convert string to camelCase. @@ -189,7 +186,7 @@ Convert string to camelCase. - `s` (`string`): Input string. -**Return**: +**Returns**: - `camelCased` (`string`): Camel-cased string. @@ -200,9 +197,9 @@ camel("foo_bar-baz") --> "fooBarBaz" camel("FooBar baz") --> "fooBarBaz" ``` - +--- -#### `constant(s)` +#### `constant(s)` {#constant} Convert string to CONSTANT_CASE (uppercase snake_case). @@ -210,7 +207,7 @@ Convert string to CONSTANT_CASE (uppercase snake_case). - `s` (`string`): Input string. -**Return**: +**Returns**: - `constantCased` (`string`): Constant-cased string. @@ -221,9 +218,9 @@ constant("foo_bar-baz") --> "FOO_BAR_BAZ" constant("FooBar baz") --> "FOO_BAR_BAZ" ``` - +--- -#### `delimit(s, sep?)` +#### `delimit(s, sep?)` {#delimit} Normalize to snake_case, then delimit words with a separator. @@ -232,7 +229,7 @@ Normalize to snake_case, then delimit words with a separator. - `s` (`string`): Input string. - `sep?` (`string`): Optional separator value (defaults to `""`). -**Return**: +**Returns**: - `delimited` (`string`): String with normalized words separated by `sep`. @@ -243,9 +240,9 @@ delimit("foo_bar-baz", "-") --> "foo-bar-baz" delimit("FooBar baz", "-") --> "foo-bar-baz" ``` - +--- -#### `dot(s)` +#### `dot(s)` {#dot} Convert string to dot.case. @@ -253,7 +250,7 @@ Convert string to dot.case. - `s` (`string`): Input string. -**Return**: +**Returns**: - `dotCased` (`string`): Dot-cased string. @@ -264,9 +261,9 @@ dot("foo_bar-baz") --> "foo.bar.baz" dot("FooBar baz") --> "foo.bar.baz" ``` - +--- -#### `kebab(s)` +#### `kebab(s)` {#kebab} Convert string to kebab-case. @@ -274,7 +271,7 @@ Convert string to kebab-case. - `s` (`string`): Input string. -**Return**: +**Returns**: - `kebabCased` (`string`): Kebab-cased string. @@ -285,9 +282,9 @@ kebab("foo_bar-baz") --> "foo-bar-baz" kebab("FooBar baz") --> "foo-bar-baz" ``` - +--- -#### `pascal(s)` +#### `pascal(s)` {#pascal} Convert string to PascalCase. @@ -295,7 +292,7 @@ Convert string to PascalCase. - `s` (`string`): Input string. -**Return**: +**Returns**: - `pascalCased` (`string`): Pascal-cased string. @@ -306,9 +303,9 @@ pascal("foo_bar-baz") --> "FooBarBaz" pascal("FooBar baz") --> "FooBarBaz" ``` - +--- -#### `path(s)` +#### `path(s)` {#path} Convert string to path/case (slashes between words). @@ -316,7 +313,7 @@ Convert string to path/case (slashes between words). - `s` (`string`): Input string. -**Return**: +**Returns**: - `pathCased` (`string`): Path-cased string. @@ -327,9 +324,9 @@ path("foo_bar-baz") --> "foo/bar/baz" path("FooBar baz") --> "foo/bar/baz" ``` - +--- -#### `snake(s)` +#### `snake(s)` {#snake} Convert string to snake_case. @@ -337,7 +334,7 @@ Convert string to snake_case. - `s` (`string`): Input string. -**Return**: +**Returns**: - `snakeCased` (`string`): Snake-cased string. @@ -348,9 +345,9 @@ snake("foo_bar-baz") --> "foo_bar_baz" snake("FooBar baz") --> "foo_bar_baz" ``` - +--- -#### `space(s)` +#### `space(s)` {#space} Convert string to space case (spaces between words). @@ -358,7 +355,7 @@ Convert string to space case (spaces between words). - `s` (`string`): Input string. -**Return**: +**Returns**: - `spaceCased` (`string`): Space-cased string. @@ -369,9 +366,9 @@ space("foo_bar-baz") --> "foo bar baz" space("FooBar baz") --> "foo bar baz" ``` - +--- -#### `title(s)` +#### `title(s)` {#title} Convert string to Title Case (first letter of each word capitalized). @@ -379,7 +376,7 @@ Convert string to Title Case (first letter of each word capitalized). - `s` (`string`): Input string. -**Return**: +**Returns**: - `titleCased` (`string`): Title-cased string. @@ -389,3 +386,22 @@ Convert string to Title Case (first letter of each word capitalized). title("foo_bar-baz") --> "Foo Bar Baz" title("FooBar baz") --> "Foo Bar Baz" ``` + + +[`acronym(s)`]: #acronym +[`camel(s)`]: #camel +[`capitalize(s)`]: #capitalize +[`constant(s)`]: #constant +[`delimit(s, sep?)`]: #delimit +[`dot(s)`]: #dot +[`kebab(s)`]: #kebab +[`lower(s)`]: #lower +[`pascal(s)`]: #pascal +[`path(s)`]: #path +[`sentence(s)`]: #sentence +[`snake(s)`]: #snake +[`space(s)`]: #space +[`swapcase(s)`]: #swapcase +[`title(s)`]: #title +[`upper(s)`]: #upper + diff --git a/docs/api/stringify.md b/docs/api/stringify.md index 7d6a3b2..d03d420 100644 --- a/docs/api/stringify.md +++ b/docs/api/stringify.md @@ -1,9 +1,8 @@ --- +title: "stringify" description: "Render Lua values as readable source-like text." --- -# `stringify` - Render Lua values as readable source-like text. ## Usage @@ -20,9 +19,7 @@ print(stringify(t)) --> } ``` - - -## `stringify(value, opts?)` +## `stringify(value, opts?)` {#stringify} Render Lua values as readable source-like text. @@ -33,7 +30,7 @@ Render Lua values as readable source-like text. (`{omit_array_keys?:boolean, indent?:string, newline?:string, replacer?:fun(k,v):(result:any)}`): Rendering options. -**Return**: +**Returns**: - `out` (`string`): Readable string representation. diff --git a/docs/api/tbl.md b/docs/api/tbl.md index 28c8f22..3e447b2 100644 --- a/docs/api/tbl.md +++ b/docs/api/tbl.md @@ -1,16 +1,15 @@ --- +title: "tbl" description: "Table operations for querying, copying, merging, and transforming tables." --- -# `tbl` - Table operations for querying, copying, merging, and transforming tables. ## Usage ```lua -tbl = require "mods.tbl" +tbl = mods.tbl print(tbl.count({ a = 1, b = 2 })) --> 2 ``` @@ -19,52 +18,50 @@ print(tbl.count({ a = 1, b = 2 })) --> 2 **Copies**: -| Function | Description | -| ----------------------------- | ----------------------------------- | -| [`copy(t)`](#fn-copy) | Create a shallow copy of the table. | -| [`deepcopy(v)`](#fn-deepcopy) | Create a deep copy of a value. | +| Function | Description | +| --------------- | ----------------------------------- | +| [`copy(t)`] | Create a shallow copy of the table. | +| [`deepcopy(v)`] | Create a deep copy of a value. | **Core Utilities**: -| Function | Description | -| ----------------------- | --------------------------------------- | -| [`clear(t)`](#fn-clear) | Remove all entries from the table. | -| [`count(t)`](#fn-count) | Return the number of keys in the table. | +| Function | Description | +| ------------ | --------------------------------------- | +| [`clear(t)`] | Remove all entries from the table. | +| [`count(t)`] | Return the number of keys in the table. | **Iterators**: -| Function | Description | -| ------------------------------- | -------------------------------------------- | -| [`foreach(t, fn)`](#fn-foreach) | Call a function for each value in the table. | -| [`spairs(t)`](#fn-spairs) | Iterate key-value pairs in sorted key order. | +| Function | Description | +| ------------------ | -------------------------------------------- | +| [`foreach(t, fn)`] | Call a function for each value in the table. | +| [`spairs(t)`] | Iterate key-value pairs in sorted key order. | **Queries**: -| Function | Description | -| ------------------------------------ | ---------------------------------------------------------------- | -| [`deep_equal(a, b)`](#fn-deep-equal) | Return `true` if two tables are deeply equal. | -| [`filter(t, pred)`](#fn-filter) | Filter entries by a value predicate. | -| [`find(t, v)`](#fn-find) | Find the first key whose value equals the given value. | -| [`find_if(t, pred)`](#fn-find-if) | Find first value and key matching predicate. | -| [`get(t, ...)`](#fn-get) | Safely get nested value by keys. | -| [`is_same(a, b)`](#fn-is-same) | Return `true` if two tables have the same keys and equal values. | +| Function | Description | +| -------------------- | ---------------------------------------------------------------- | +| [`deep_equal(a, b)`] | Return `true` if two tables are deeply equal. | +| [`filter(t, pred)`] | Filter entries by a value predicate. | +| [`find(t, v)`] | Find the first key whose value equals the given value. | +| [`find_if(t, pred)`] | Find first value and key matching predicate. | +| [`get(t, ...)`] | Safely get nested value by keys. | +| [`is_same(a, b)`] | Return `true` if two tables have the same keys and equal values. | **Transforms**: -| Function | Description | -| ------------------------------ | -------------------------------------------------- | -| [`invert(t)`](#fn-invert) | Invert keys/values into new table. | -| [`isempty(t)`](#fn-isempty) | Return true if table has no entries. | -| [`keys(t)`](#fn-keys) | Return a list of all keys in the table. | -| [`map(t, fn)`](#fn-map) | Return a new table by mapping each key-value pair. | -| [`update(t1, t2)`](#fn-update) | Merge entries from `t2` into `t1` and return `t1`. | -| [`values(t)`](#fn-values) | Return a list of all values in the table. | +| Function | Description | +| ------------------ | -------------------------------------------------- | +| [`invert(t)`] | Invert keys/values into new table. | +| [`isempty(t)`] | Return true if table has no entries. | +| [`keys(t)`] | Return a list of all keys in the table. | +| [`map(t, fn)`] | Return a new table by mapping each key-value pair. | +| [`update(t1, t2)`] | Merge entries from `t2` into `t1` and return `t1`. | +| [`values(t)`] | Return a list of all values in the table. | ### Copies - - -#### `copy(t)` +#### `copy(t)` {#copy} Create a shallow copy of the table. @@ -72,7 +69,7 @@ Create a shallow copy of the table. - `t` (`T`): Source table. -**Return**: +**Returns**: - `copy` (`T`): Shallow-copied table. @@ -82,9 +79,9 @@ Create a shallow copy of the table. t = copy({ a = 1, b = 2 }) --> { a = 1, b = 2 } ``` - +--- -#### `deepcopy(v)` +#### `deepcopy(v)` {#deepcopy} Create a deep copy of a value. @@ -92,7 +89,7 @@ Create a deep copy of a value. - `v` (`T`): Input value. -**Return**: +**Returns**: - `copiedValue` (`T`): Deep-copied value. @@ -108,11 +105,11 @@ n = deepcopy(42) --> 42 > If `v` is a table, all nested tables are copied recursively; other types are > returned as-is. -### Core Utilities +--- - +### Core Utilities -#### `clear(t)` +#### `clear(t)` {#clear} Remove all entries from the table. @@ -120,7 +117,7 @@ Remove all entries from the table. - `t` (`table`): Target table. -**Return**: +**Returns**: - `none` (`nil`) @@ -131,9 +128,9 @@ t = { a = 1, b = 2 } clear(t) --> t = {} ``` - +--- -#### `count(t)` +#### `count(t)` {#count} Return the number of keys in the table. @@ -141,7 +138,7 @@ Return the number of keys in the table. - `t` (`table`): Input table. -**Return**: +**Returns**: - `count` (`integer`): Number of keys in `t`. @@ -151,11 +148,11 @@ Return the number of keys in the table. n = count({ a = 1, b = 2 }) --> 2 ``` -### Iterators +--- - +### Iterators -#### `foreach(t, fn)` +#### `foreach(t, fn)` {#foreach} Call a function for each value in the table. @@ -164,7 +161,7 @@ Call a function for each value in the table. - `t` (`table`): Input table. - `fn` (`fun(value:V, key:K)`): Function invoked for each entry. -**Return**: +**Returns**: - `none` (`nil`) @@ -176,9 +173,9 @@ foreach({ a = 1, b = 2 }, function(v, k) end) ``` - +--- -#### `spairs(t)` +#### `spairs(t)` {#spairs} Iterate key-value pairs in sorted key order. @@ -186,7 +183,7 @@ Iterate key-value pairs in sorted key order. - `t` (`T`): Input table. -**Return**: +**Returns**: - `iterator` (`fun(table: table, index?: K):(K, V)`): Sorted pairs iterator. @@ -200,11 +197,11 @@ for k, v in spairs({ b = 2, a = 1 }) do end ``` -### Queries +--- - +### Queries -#### `deep_equal(a, b)` +#### `deep_equal(a, b)` {#deep-equal} Return `true` if two tables are deeply equal. @@ -213,7 +210,7 @@ Return `true` if two tables are deeply equal. - `a` (`table`): Left table. - `b` (`table`): Right table. -**Return**: +**Returns**: - `isDeepEqual` (`boolean`): True when both tables are recursively equal. @@ -224,9 +221,9 @@ ok = deep_equal({ a = { b = 1 } }, { a = { b = 1 } }) --> true ok = deep_equal({ a = { b = 1 } }, { a = { b = 2 } }) --> false ``` - +--- -#### `filter(t, pred)` +#### `filter(t, pred)` {#filter} Filter entries by a value predicate. @@ -235,7 +232,7 @@ Filter entries by a value predicate. - `t` (`table`): Input table. - `pred` (`fun(value:V):boolean`): Value predicate. -**Return**: +**Returns**: - `filtered` (`table`): Table containing entries where `pred(v)` is true. @@ -247,9 +244,9 @@ even = filter({ a = 1, b = 2, c = 3 }, function(v) end) --> { b = 2 } ``` - +--- -#### `find(t, v)` +#### `find(t, v)` {#find} Find the first key whose value equals the given value. @@ -258,9 +255,9 @@ Find the first key whose value equals the given value. - `t` (`table`): Input table. - `v` (`V`): Value to find. -**Return**: +**Returns**: -- `key` (`K?`): First matching key, or `nil` when not found. +- `key?` (`K`): First matching key, or `nil` when not found. **Example**: @@ -268,9 +265,9 @@ Find the first key whose value equals the given value. key = find({ a = 1, b = 2, c = 2 }, 2) --> "b" or "c" ``` - +--- -#### `find_if(t, pred)` +#### `find_if(t, pred)` {#find-if} Find first value and key matching predicate. @@ -279,10 +276,10 @@ Find first value and key matching predicate. - `t` (`table`): Input table. - `pred` (`fun(key:K,value:V):boolean`): Predicate function. -**Return**: +**Returns**: -- `value` (`V?`): First matching value, or `nil` when not found. -- `key` (`K?`): Key for the first matching value, or `nil` when not found. +- `value?` (`V`): First matching value, or `nil` when not found. +- `key?` (`K`): Key for the first matching value, or `nil` when not found. **Example**: @@ -292,9 +289,9 @@ v, k = find_if({ a = 1, b = 2 }, function(v, k) end) --> 2, "b" ``` - +--- -#### `get(t, ...)` +#### `get(t, ...)` {#get} Safely get nested value by keys. @@ -303,7 +300,7 @@ Safely get nested value by keys. - `t` (`table`): Root table. - `...` (`any`): Additional arguments. -**Return**: +**Returns**: - `nestedValue` (`any`): Nested value, or `nil` when any key is missing. @@ -319,9 +316,9 @@ v2 = get(t) --> { a = { b = { c = 1 } } } > > If no keys are provided, returns the input table. - +--- -#### `is_same(a, b)` +#### `is_same(a, b)` {#is-same} Return `true` if two tables have the same keys and equal values. @@ -330,7 +327,7 @@ Return `true` if two tables have the same keys and equal values. - `a` (`table`): Left table. - `b` (`table`): Right table. -**Return**: +**Returns**: - `isSame` (`boolean`): True when both tables have the same keys and values. @@ -341,11 +338,11 @@ ok = is_same({ a = 1, b = 2 }, { b = 2, a = 1 }) --> true ok = is_same({ a = {} }, { a = {} }) --> false ``` -### Transforms +--- - +### Transforms -#### `invert(t)` +#### `invert(t)` {#invert} Invert keys/values into new table. @@ -353,7 +350,7 @@ Invert keys/values into new table. - `t` (`table`): Input table. -**Return**: +**Returns**: - `inverted` (`table`): Inverted table (`value -> key`). @@ -363,9 +360,9 @@ Invert keys/values into new table. t = invert({ a = 1, b = 2 }) --> { [1] = "a", [2] = "b" } ``` - +--- -#### `isempty(t)` +#### `isempty(t)` {#isempty} Return true if table has no entries. @@ -373,7 +370,7 @@ Return true if table has no entries. - `t` (`table`): Input table. -**Return**: +**Returns**: - `isEmpty` (`boolean`): True when `t` has no entries. @@ -383,9 +380,9 @@ Return true if table has no entries. empty = isempty({}) --> true ``` - +--- -#### `keys(t)` +#### `keys(t)` {#keys} Return a list of all keys in the table. @@ -393,9 +390,9 @@ Return a list of all keys in the table. - `t` (`table`): Input table. -**Return**: +**Returns**: -- `keys` (`mods.List`): List of keys in `t`. +- `keys` ([`mods.List`]``): List of keys in `t`. **Example**: @@ -403,9 +400,9 @@ Return a list of all keys in the table. keys = keys({ a = 1, b = 2 }) --> { "a", "b" } ``` - +--- -#### `map(t, fn)` +#### `map(t, fn)` {#map} Return a new table by mapping each key-value pair. @@ -414,7 +411,7 @@ Return a new table by mapping each key-value pair. - `t` (`table`): Input table. - `fn` (`fun(key:K, value:V):T`): Key-value mapping function. -**Return**: +**Returns**: - `mapped` (`table`): New table with mapped values. @@ -430,9 +427,9 @@ end) --> { a = "a1", b = "b2" } > > Output keeps original keys; only values are transformed by `fn`. - +--- -#### `update(t1, t2)` +#### `update(t1, t2)` {#update} Merge entries from `t2` into `t1` and return `t1`. @@ -441,7 +438,7 @@ Merge entries from `t2` into `t1` and return `t1`. - `t1` (`T`): Target table. - `t2` (`table`): Source table. -**Return**: +**Returns**: - `table` (`T`): Updated `t1` table. @@ -452,9 +449,9 @@ t1 = { a = 1, b = 2 } update(t1, { b = 3, c = 4 }) --> t1 is { a = 1, b = 3, c = 4 } ``` - +--- -#### `values(t)` +#### `values(t)` {#values} Return a list of all values in the table. @@ -462,12 +459,34 @@ Return a list of all values in the table. - `t` (`table`): Input table. -**Return**: +**Returns**: -- `values` (`mods.List`): List of values in `t`. +- `values` ([`mods.List`]``): List of values in `t`. **Example**: ```lua vals = values({ a = 1, b = 2 }) --> { 1, 2 } ``` + + +[`clear(t)`]: #clear +[`copy(t)`]: #copy +[`count(t)`]: #count +[`deep_equal(a, b)`]: #deep-equal +[`deepcopy(v)`]: #deepcopy +[`filter(t, pred)`]: #filter +[`find(t, v)`]: #find +[`find_if(t, pred)`]: #find-if +[`foreach(t, fn)`]: #foreach +[`get(t, ...)`]: #get +[`invert(t)`]: #invert +[`is_same(a, b)`]: #is-same +[`isempty(t)`]: #isempty +[`keys(t)`]: #keys +[`map(t, fn)`]: #map +[`mods.List`]: /mods/api/list +[`spairs(t)`]: #spairs +[`update(t1, t2)`]: #update +[`values(t)`]: #values + diff --git a/docs/api/template.md b/docs/api/template.md index 0d5bdc2..0cc16a3 100644 --- a/docs/api/template.md +++ b/docs/api/template.md @@ -1,15 +1,14 @@ --- -description: "String template rendering with {{." +title: "template" +description: "String template rendering with {{." --- -# `template` - String template rendering with {{...}} placeholders. ## Usage ```lua -template = require "mods.template" +template = mods.template view = { user = { name = "Ada" }, @@ -18,9 +17,7 @@ view = { out = template("Hello {{user.name}}!", view) --> "Hello Ada!" ``` - - -## `template(tmpl, view)` +## `template(tmpl, view)` {#template} Render string templates with {{...}} placeholders. @@ -29,7 +26,7 @@ Render string templates with {{...}} placeholders. - `tmpl` (`string`): Template string with placeholders. - `view` (`table`): Input data used to resolve placeholders. -**Return**: +**Returns**: - `out` (`string`): Rendered output string. @@ -85,7 +82,7 @@ template("Hi {{name_func}}", view) --> "Hi Ada" ## Table Values -Table placeholders are rendered using `mods.stringify`. +Table placeholders are rendered using [`mods.stringify`]. ```lua view = { data = { a = 1, b = true } } @@ -121,3 +118,7 @@ as-is. view = { name = "Ada" } template("Hi {{name", view) --> "Hi {{name" ``` + + +[`mods.stringify`]: /mods/api/stringify + diff --git a/docs/api/utils.md b/docs/api/utils.md index 1309acd..dea82f2 100644 --- a/docs/api/utils.md +++ b/docs/api/utils.md @@ -1,15 +1,14 @@ --- +title: "utils" description: "Shared utility helpers used across the Mods library." --- -# `utils` - Shared utility helpers used across the Mods library. ## Usage ```lua -utils = require "mods.utils" +utils = mods.utils print(utils.quote('hello "world"')) --> 'hello "world"' ``` @@ -18,31 +17,29 @@ print(utils.quote('hello "world"')) --> 'hello "world"' **Formatting**: -| Function | Description | -| ------------------------------- | -------------------------------------------------------------- | -| [`args_repr(v)`](#fn-args-repr) | Format a list-like table as a comma-separated argument string. | -| [`keypath(...)`](#fn-keypath) | Format a key chain as a Lua-like table access path. | -| [`quote(v)`](#fn-quote) | Smart-quote a string for readable Lua-like output. | +| Function | Description | +| ---------------- | -------------------------------------------------------------- | +| [`args_repr(v)`] | Format a list-like table as a comma-separated argument string. | +| [`keypath(...)`] | Format a key chain as a Lua-like table access path. | +| [`quote(v)`] | Smart-quote a string for readable Lua-like output. | **Lazy Loading**: -| Function | Description | -| -------------------------------------------- | --------------------------------- | -| [`lazy_module(name, err?)`](#fn-lazy-module) | Return a lazy proxy for a module. | +| Function | Description | +| --------------------------- | --------------------------------- | +| [`lazy_module(name, err?)`] | Return a lazy proxy for a module. | **Validation**: -| Function | Description | -| ------------------------------------------------------------------- | ----------------------------------------------------------------------------- | -| [`assert_arg(argn, v, validator?, optional?, lv?)`](#fn-assert-arg) | Assert argument value using `mods.validate` and raise a Lua error on failure. | -| [`validate(name, v, validator?, optional?, msg?)`](#fn-validate) | Validate a value using `mods.validate` and raise a Lua error on failure. | -| [`validate(path, v, validator?, optional?, msg?)`](#fn-validate) | Validate a value using `mods.validate` and raise a Lua error on failure. | +| Function | Description | +| --------------------------------------------------- | ------------------------------------------------------------------------------- | +| [`assert_arg(argn, v, validator?, optional?, lv?)`] | Assert argument value using [`mods.validate`] and raise a Lua error on failure. | +| [`validate(name, v, validator?, optional?, msg?)`] | Validate a value using [`mods.validate`] and raise a Lua error on failure. | +| [`validate(path, v, validator?, optional?, msg?)`] | Validate a value using [`mods.validate`] and raise a Lua error on failure. | ### Formatting - - -#### `args_repr(v)` +#### `args_repr(v)` {#args-repr} Format a list-like table as a comma-separated argument string. @@ -50,7 +47,7 @@ Format a list-like table as a comma-separated argument string. - `v` (`any`): Value to format. `nil` returns an empty string. -**Return**: +**Returns**: - `out` (`string`): Argument list string. @@ -60,9 +57,9 @@ Format a list-like table as a comma-separated argument string. utils.args_repr({ "a", 1, true }) --> '"a", 1, true' ``` - +--- -#### `keypath(...)` +#### `keypath(...)` {#keypath} Format a key chain as a Lua-like table access path. @@ -70,7 +67,7 @@ Format a key chain as a Lua-like table access path. - `...` (`any`): Additional arguments. -**Return**: +**Returns**: - `path` (`string`): Rendered key path. @@ -83,9 +80,9 @@ p3 = utils.keypath("ctx", "invalid-key") --> 'ctx["invalid-key"]' p4 = utils.keypath() --> "" ``` - +--- -#### `quote(v)` +#### `quote(v)` {#quote} Smart-quote a string for readable Lua-like output. @@ -93,7 +90,7 @@ Smart-quote a string for readable Lua-like output. - `v` (`string`): String to quote. -**Return**: +**Returns**: - `out` (`string`): Quoted string. @@ -104,11 +101,11 @@ print(utils.quote('He said "hi"')) -- 'He said "hi"' print(utils.quote('say "hi" and \\'bye\\'')) -- "say \"hi\" and 'bye'" ``` -### Lazy Loading +--- - +### Lazy Loading -#### `lazy_module(name, err?)` +#### `lazy_module(name, err?)` {#lazy-module} Return a lazy proxy for a module. @@ -120,7 +117,7 @@ table itself free of cached fields. - `name` (`string`): Module name passed to `require`. - `err?` (`string`): Optional error message raised when loading fails. -**Return**: +**Returns**: - `module` (`{}`): Lazy proxy for the loaded module. @@ -138,23 +135,24 @@ print(stringify({ a = 1 })) > > Supports both table-returning modules and function-returning modules. -### Validation +--- - +### Validation -#### `assert_arg(argn, v, validator?, optional?, lv?)` +#### `assert_arg(argn, v, validator?, optional?, lv?)` {#assert-arg} -Assert argument value using `mods.validate` and raise a Lua error on failure. +Assert argument value using [`mods.validate`] and raise a Lua error on failure. **Parameters**: - `argn` (`integer`): Argument index for error context. - `v` (`T`): Value to check. -- `validator?` (`modsValidatorName`): Validator name (defaults to `"truthy"`). +- `validator?` ([`mods.ValidatorName`]): Validator name (defaults to + `"truthy"`). - `optional?` (`boolean`): Skip errors when `v` is `nil` (defaults to `false`). - `lv?` (`integer`): Error level passed to `error` (defaults to `3`). -**Return**: +**Returns**: - `validatedValue` (`T`): Same input value on success, or `nil` when optional. @@ -174,21 +172,22 @@ utils.assert_arg(3, "x", "number", false, "need {{expected}}, got {{got}}") > When the caller function name is available, error text includes > `to ''` (Lua-style bad argument context). - +--- -#### `validate(name, v, validator?, optional?, msg?)` +#### `validate(name, v, validator?, optional?, msg?)` {#validate} -Validate a value using `mods.validate` and raise a Lua error on failure. +Validate a value using [`mods.validate`] and raise a Lua error on failure. **Parameters**: - `name` (`string`): Name for the error prefix. - `v` (`any`): Value to validate. -- `validator?` (`modsValidatorName`): Validator name (defaults to `"truthy"`). +- `validator?` ([`mods.ValidatorName`]): Validator name (defaults to + `"truthy"`). - `optional?` (`boolean`): Skip errors when `v` is `nil` (defaults to `false`). -- `msg?` (`string`): Optional override template passed to `mods.validate`. +- `msg?` (`string`): Optional override template passed to [`mods.validate`]. -**Return**: +**Returns**: - `none` (`nil`) @@ -201,21 +200,22 @@ utils.validate("count", "x", "number") --> raises: count: expected number, got string ``` - +--- -#### `validate(path, v, validator?, optional?, msg?)` +#### `validate(path, v, validator?, optional?, msg?)` {#validate-1} -Validate a value using `mods.validate` and raise a Lua error on failure. +Validate a value using [`mods.validate`] and raise a Lua error on failure. **Parameters**: - `path` (`table`): Path parts for the error name. - `v` (`any`): Value to validate. -- `validator?` (`modsValidatorName`): Validator name (defaults to `"truthy"`). +- `validator?` ([`mods.ValidatorName`]): Validator name (defaults to + `"truthy"`). - `optional?` (`boolean`): Skip errors when `v` is `nil` (defaults to `false`). -- `msg?` (`string`): Optional override template passed to `mods.validate`. +- `msg?` (`string`): Optional override template passed to [`mods.validate`]. -**Return**: +**Returns**: - `none` (`nil`) @@ -229,4 +229,17 @@ utils.validate({ "ctx", "users", 1, "name" }, 123, "string") > [!NOTE] > -> On failure, `path` is rendered with `mods.utils.keypath`. +> On failure, `path` is rendered with [`mods.utils.keypath`]. + + +[`args_repr(v)`]: #args-repr +[`assert_arg(argn, v, validator?, optional?, lv?)`]: #assert-arg +[`keypath(...)`]: #keypath +[`lazy_module(name, err?)`]: #lazy-module +[`mods.ValidatorName`]: /mods/types#mods-validatorname +[`mods.utils.keypath`]: /mods/api/utils#keypath +[`mods.validate`]: /mods/api/validate +[`quote(v)`]: #quote +[`validate(name, v, validator?, optional?, msg?)`]: #validate +[`validate(path, v, validator?, optional?, msg?)`]: #validate-1 + diff --git a/docs/api/validate.md b/docs/api/validate.md index 196af83..501e948 100644 --- a/docs/api/validate.md +++ b/docs/api/validate.md @@ -1,15 +1,14 @@ --- +title: "validate" description: "Validation helpers for Lua values and filesystem path types." --- -# `validate` - Validation helpers for Lua values and filesystem path types. ## Usage ```lua -local validate = require "mods.validate" +local validate = mods.validate ok, err = validate.number("nope") --> false, "number expected, got string" ok, err = validate(123, "number") --> true, nil @@ -28,9 +27,8 @@ validate(1, "nil") --> false, "nil expected, got number" > [!IMPORTANT] > -> Path checks require **LuaFileSystem** -> ([`lfs`](https://github.com/lunarmodules/luafilesystem)) and raise an error if -> it is not installed. +> Path checks require **LuaFileSystem** ([`lfs`]) and raise an error if it is +> not installed. ## Validator Names @@ -61,57 +59,102 @@ validate.string(123, "want {{expected}}, got {{got}}") --> false, "want string, got number" ``` +## Fields + +### `messages` (`modsValidatorMessages`) {#messages} + +Custom error-message templates for validator failures. + +Set `validate.messages.`, where `` is a validator name (for example: +`number`, `truthy`, `file`). + +The error-message template is used only when validation fails and an error +message is returned. + +```lua +validate.messages.number = "need {{expected}}, got {{got}}" +ok, err = validate.number("x") --> false, "need number, got string" +``` + +**Placeholders**: + +- {{expected}}: The check target (for example `number`, + `string`, `truthy`). +- {{got}}: The detected failure kind (usually a Lua type; + path validators use `invalid path`). +- {{value}}: The passed value, formatted for display (strings + are quoted). + +> [!NOTE] +> +> When the passed value is `nil`, rendered value text uses `no value`. +> +> ```lua +> validate.messages.truthy = "{{expected}} value expected, got {{value}}" +> validate.truthy(nil) --> false, "truthy value expected, got no value" +> ``` + +**Default Messages**: + +- Type checks: {{expected}} expected, got {{got}} +- Value checks: {{expected}} value expected, got {{value}} +- Path checks: {{value}} is not a valid {{expected}} path + (for `path`: {{value}} is not a valid path) + +> [!NOTE] +> +> For path checks, if the value is not a `string`, the message falls back to +> `messages.string` (as if `validate.string` was called). + ## Functions **Path Checks**: -| Function | Description | -| ------------------------------- | ------------------------------------------------------------------------------------------------------- | -| [`block(v, msg?)`](#fn-block) | Returns `true` when `v` is a block device path. Otherwise returns `false` and an error message. | -| [`char(v, msg?)`](#fn-char) | Returns `true` when `v` is a char device path. Otherwise returns `false` and an error message. | -| [`device(v, msg?)`](#fn-device) | Returns `true` when `v` is a block or char device path. Otherwise returns `false` and an error message. | -| [`dir(v, msg?)`](#fn-dir) | Returns `true` when `v` is a directory path. Otherwise returns `false` and an error message. | -| [`fifo(v, msg?)`](#fn-fifo) | Returns `true` when `v` is a FIFO path. Otherwise returns `false` and an error message. | -| [`file(v, msg?)`](#fn-file) | Returns `true` when `v` is a file path. Otherwise returns `false` and an error message. | -| [`link(v, msg?)`](#fn-link) | Returns `true` when `v` is a symlink path. Otherwise returns `false` and an error message. | -| [`path(v, msg?)`](#fn-path) | Returns `true` when `v` is a valid filesystem path. Otherwise returns `false` and an error message. | -| [`socket(v, msg?)`](#fn-socket) | Returns `true` when `v` is a socket path. Otherwise returns `false` and an error message. | +| Function | Description | +| ------------------- | ------------------------------------------------------------------------------------------------------- | +| [`block(v, msg?)`] | Returns `true` when `v` is a block device path. Otherwise returns `false` and an error message. | +| [`char(v, msg?)`] | Returns `true` when `v` is a char device path. Otherwise returns `false` and an error message. | +| [`device(v, msg?)`] | Returns `true` when `v` is a block or char device path. Otherwise returns `false` and an error message. | +| [`dir(v, msg?)`] | Returns `true` when `v` is a directory path. Otherwise returns `false` and an error message. | +| [`fifo(v, msg?)`] | Returns `true` when `v` is a FIFO path. Otherwise returns `false` and an error message. | +| [`file(v, msg?)`] | Returns `true` when `v` is a file path. Otherwise returns `false` and an error message. | +| [`link(v, msg?)`] | Returns `true` when `v` is a symlink path. Otherwise returns `false` and an error message. | +| [`path(v, msg?)`] | Returns `true` when `v` is a valid filesystem path. Otherwise returns `false` and an error message. | +| [`socket(v, msg?)`] | Returns `true` when `v` is a socket path. Otherwise returns `false` and an error message. | **Registration**: -| Function | Description | -| ------------------------------------------------------ | -------------------------------------------------- | -| [`register(name, validator, template?)`](#fn-register) | Register or override a validator function by name. | +| Function | Description | +| ---------------------------------------- | -------------------------------------------------- | +| [`register(name, validator, template?)`] | Register or override a validator function by name. | **Type Checks**: -| Function | Description | -| ----------------------------------- | -------------------------------------------------------------------------------------------- | -| [`boolean(v, msg?)`](#fn-boolean) | Returns `true` when `v` is a boolean. Otherwise returns `false` and an error message. | -| [`function(v, msg?)`](#fn-function) | Returns `true` when `v` is a function. Otherwise returns `false` and an error message. | -| [`nil(v, msg?)`](#fn-nil) | Returns `true` when `v` is `nil`. Otherwise returns `false` and an error message. | -| [`number(v, msg?)`](#fn-number) | Returns `true` when `v` is a number. Otherwise returns `false` and an error message. | -| [`string(v, msg?)`](#fn-string) | Returns `true` when `v` is a string. Otherwise returns `false` and an error message. | -| [`table(v, msg?)`](#fn-table) | Returns `true` when `v` is a table. Otherwise returns `false` and an error message. | -| [`thread(v, msg?)`](#fn-thread) | Returns `true` when `v` is a thread. Otherwise returns `false` and an error message. | -| [`userdata(v, msg?)`](#fn-userdata) | Returns `true` when `v` is a userdata value. Otherwise returns `false` and an error message. | +| Function | Description | +| --------------------- | -------------------------------------------------------------------------------------------- | +| [`boolean(v, msg?)`] | Returns `true` when `v` is a boolean. Otherwise returns `false` and an error message. | +| [`function(v, msg?)`] | Returns `true` when `v` is a function. Otherwise returns `false` and an error message. | +| [`nil(v, msg?)`] | Returns `true` when `v` is `nil`. Otherwise returns `false` and an error message. | +| [`number(v, msg?)`] | Returns `true` when `v` is a number. Otherwise returns `false` and an error message. | +| [`string(v, msg?)`] | Returns `true` when `v` is a string. Otherwise returns `false` and an error message. | +| [`table(v, msg?)`] | Returns `true` when `v` is a table. Otherwise returns `false` and an error message. | +| [`thread(v, msg?)`] | Returns `true` when `v` is a thread. Otherwise returns `false` and an error message. | +| [`userdata(v, msg?)`] | Returns `true` when `v` is a userdata value. Otherwise returns `false` and an error message. | **Value Checks**: -| Function | Description | -| ----------------------------------- | ------------------------------------------------------------------------------------------- | -| [`callable(v, msg?)`](#fn-callable) | Returns `true` when `v` is callable. Otherwise returns `false` and an error message. | -| [`false(v, msg?)`](#fn-false) | Returns `true` when `v` is exactly `false`. Otherwise returns `false` and an error message. | -| [`falsy(v, msg?)`](#fn-falsy) | Returns `true` when `v` is falsy. Otherwise returns `false` and an error message. | -| [`integer(v, msg?)`](#fn-integer) | Returns `true` when `v` is an integer. Otherwise returns `false` and an error message. | -| [`true(v, msg?)`](#fn-true) | Returns `true` when `v` is exactly `true`. Otherwise returns `false` and an error message. | -| [`truthy(v, msg?)`](#fn-truthy) | Returns `true` when `v` is truthy. Otherwise returns `false` and an error message. | +| Function | Description | +| --------------------- | ------------------------------------------------------------------------------------------- | +| [`callable(v, msg?)`] | Returns `true` when `v` is callable. Otherwise returns `false` and an error message. | +| [`false(v, msg?)`] | Returns `true` when `v` is exactly `false`. Otherwise returns `false` and an error message. | +| [`falsy(v, msg?)`] | Returns `true` when `v` is falsy. Otherwise returns `false` and an error message. | +| [`integer(v, msg?)`] | Returns `true` when `v` is an integer. Otherwise returns `false` and an error message. | +| [`true(v, msg?)`] | Returns `true` when `v` is exactly `true`. Otherwise returns `false` and an error message. | +| [`truthy(v, msg?)`] | Returns `true` when `v` is truthy. Otherwise returns `false` and an error message. | ### Path Checks - - -#### `block(v, msg?)` +#### `block(v, msg?)` {#block} Returns `true` when `v` is a block device path. Otherwise returns `false` and an error message. @@ -121,10 +164,10 @@ error message. - `v` (`any`): Value to validate. - `msg?` (`string`): Optional override template. -**Return**: +**Returns**: - `isValid` (`boolean`): Whether the check succeeds. -- `err` (`string?`): Error message when the check fails. +- `err?` (`string`): Error message when the check fails. **Example**: @@ -132,9 +175,9 @@ error message. ok, err = validate.block(".") ``` - +--- -#### `char(v, msg?)` +#### `char(v, msg?)` {#char} Returns `true` when `v` is a char device path. Otherwise returns `false` and an error message. @@ -144,10 +187,10 @@ error message. - `v` (`any`): Value to validate. - `msg?` (`string`): Optional override template. -**Return**: +**Returns**: - `isValid` (`boolean`): Whether the check succeeds. -- `err` (`string?`): Error message when the check fails. +- `err?` (`string`): Error message when the check fails. **Example**: @@ -155,9 +198,9 @@ error message. ok, err = validate.char(".") ``` - +--- -#### `device(v, msg?)` +#### `device(v, msg?)` {#device} Returns `true` when `v` is a block or char device path. Otherwise returns `false` and an error message. @@ -167,10 +210,10 @@ Returns `true` when `v` is a block or char device path. Otherwise returns - `v` (`any`): Value to validate. - `msg?` (`string`): Optional override template. -**Return**: +**Returns**: - `isValid` (`boolean`): Whether the check succeeds. -- `err` (`string?`): Error message when the check fails. +- `err?` (`string`): Error message when the check fails. **Example**: @@ -178,9 +221,9 @@ Returns `true` when `v` is a block or char device path. Otherwise returns ok, err = validate.device(".") ``` - +--- -#### `dir(v, msg?)` +#### `dir(v, msg?)` {#dir} Returns `true` when `v` is a directory path. Otherwise returns `false` and an error message. @@ -190,10 +233,10 @@ error message. - `v` (`any`): Value to validate. - `msg?` (`string`): Optional override template. -**Return**: +**Returns**: - `isValid` (`boolean`): Whether the check succeeds. -- `err` (`string?`): Error message when the check fails. +- `err?` (`string`): Error message when the check fails. **Example**: @@ -201,9 +244,9 @@ error message. ok, err = validate.dir(".") ``` - +--- -#### `fifo(v, msg?)` +#### `fifo(v, msg?)` {#fifo} Returns `true` when `v` is a FIFO path. Otherwise returns `false` and an error message. @@ -213,10 +256,10 @@ message. - `v` (`any`): Value to validate. - `msg?` (`string`): Optional override template. -**Return**: +**Returns**: - `isValid` (`boolean`): Whether the check succeeds. -- `err` (`string?`): Error message when the check fails. +- `err?` (`string`): Error message when the check fails. **Example**: @@ -224,9 +267,9 @@ message. ok, err = validate.fifo(".") ``` - +--- -#### `file(v, msg?)` +#### `file(v, msg?)` {#file} Returns `true` when `v` is a file path. Otherwise returns `false` and an error message. @@ -236,10 +279,10 @@ message. - `v` (`any`): Value to validate. - `msg?` (`string`): Optional override template. -**Return**: +**Returns**: - `isValid` (`boolean`): Whether the check succeeds. -- `err` (`string?`): Error message when the check fails. +- `err?` (`string`): Error message when the check fails. **Example**: @@ -247,9 +290,9 @@ message. ok, err = validate.file(".") ``` - +--- -#### `link(v, msg?)` +#### `link(v, msg?)` {#link} Returns `true` when `v` is a symlink path. Otherwise returns `false` and an error message. @@ -259,10 +302,10 @@ error message. - `v` (`any`): Value to validate. - `msg?` (`string`): Optional override template. -**Return**: +**Returns**: - `isValid` (`boolean`): Whether the check succeeds. -- `err` (`string?`): Error message when the check fails. +- `err?` (`string`): Error message when the check fails. **Example**: @@ -270,9 +313,9 @@ error message. ok, err = validate.link(".") ``` - +--- -#### `path(v, msg?)` +#### `path(v, msg?)` {#path} Returns `true` when `v` is a valid filesystem path. Otherwise returns `false` and an error message. @@ -282,10 +325,10 @@ and an error message. - `v` (`any`): Value to validate. - `msg?` (`string`): Optional override template. -**Return**: +**Returns**: - `isValid` (`boolean`): Whether the check succeeds. -- `err` (`string?`): Error message when the check fails. +- `err?` (`string`): Error message when the check fails. **Example**: @@ -293,9 +336,9 @@ and an error message. ok, err = validate.path("README.md") ``` - +--- -#### `socket(v, msg?)` +#### `socket(v, msg?)` {#socket} Returns `true` when `v` is a socket path. Otherwise returns `false` and an error message. @@ -305,10 +348,10 @@ message. - `v` (`any`): Value to validate. - `msg?` (`string`): Optional override template. -**Return**: +**Returns**: - `isValid` (`boolean`): Whether the check succeeds. -- `err` (`string?`): Error message when the check fails. +- `err?` (`string`): Error message when the check fails. **Example**: @@ -316,11 +359,11 @@ message. ok, err = validate.socket(".") ``` -### Registration +--- - +### Registration -#### `register(name, validator, template?)` +#### `register(name, validator, template?)` {#register} Register or override a validator function by name. @@ -330,7 +373,7 @@ Register or override a validator function by name. - `validator` (`fun(v:any):(ok:boolean)`): Validator function. - `template?` (`string`): Optional default message template. -**Return**: +**Returns**: - `none` (`nil`) @@ -353,11 +396,11 @@ ok, err = validate(2, "odd") --> false, "2 does not satisfy odd" > - If `template` is omitted, failures use: > `{{expected}} expected, got {{got}}`. -### Type Checks +--- - +### Type Checks -#### `boolean(v, msg?)` +#### `boolean(v, msg?)` {#boolean} Returns `true` when `v` is a boolean. Otherwise returns `false` and an error message. @@ -367,10 +410,10 @@ message. - `v` (`any`): Value to validate. - `msg?` (`string`): Optional override template. -**Return**: +**Returns**: - `isValid` (`boolean`): Whether the check succeeds. -- `err` (`string?`): Error message when the check fails. +- `err?` (`string`): Error message when the check fails. **Example**: @@ -379,9 +422,9 @@ ok, err = validate.boolean(true) --> true, nil ok, err = validate.boolean(1) --> false, "boolean expected, got number" ``` - +--- -#### `function(v, msg?)` +#### `function(v, msg?)` {#function} Returns `true` when `v` is a function. Otherwise returns `false` and an error message. @@ -391,10 +434,10 @@ message. - `v` (`any`): Value to validate. - `msg?` (`string`): Optional override template. -**Return**: +**Returns**: - `isValid` (`boolean`): Whether the check succeeds. -- `err` (`string?`): Error message when the check fails. +- `err?` (`string`): Error message when the check fails. **Example**: @@ -404,9 +447,9 @@ ok, err = validate.Function(1) --> false, "function expected, got number" ``` - +--- -#### `nil(v, msg?)` +#### `nil(v, msg?)` {#nil} Returns `true` when `v` is `nil`. Otherwise returns `false` and an error message. @@ -416,10 +459,10 @@ message. - `v` (`any`): Value to validate. - `msg?` (`string`): Optional override template. -**Return**: +**Returns**: - `isValid` (`boolean`): Whether the check succeeds. -- `err` (`string?`): Error message when the check fails. +- `err?` (`string`): Error message when the check fails. **Example**: @@ -428,9 +471,9 @@ ok, err = validate.Nil(nil) --> true, nil ok, err = validate.Nil(0) --> false, "nil expected, got number" ``` - +--- -#### `number(v, msg?)` +#### `number(v, msg?)` {#number} Returns `true` when `v` is a number. Otherwise returns `false` and an error message. @@ -440,10 +483,10 @@ message. - `v` (`any`): Value to validate. - `msg?` (`string`): Optional override template. -**Return**: +**Returns**: - `isValid` (`boolean`): Whether the check succeeds. -- `err` (`string?`): Error message when the check fails. +- `err?` (`string`): Error message when the check fails. **Example**: @@ -452,9 +495,9 @@ ok, err = validate.number(42) --> true, nil ok, err = validate.number("x") --> false, "number expected, got string" ``` - +--- -#### `string(v, msg?)` +#### `string(v, msg?)` {#string} Returns `true` when `v` is a string. Otherwise returns `false` and an error message. @@ -464,10 +507,10 @@ message. - `v` (`any`): Value to validate. - `msg?` (`string`): Optional override template. -**Return**: +**Returns**: - `isValid` (`boolean`): Whether the check succeeds. -- `err` (`string?`): Error message when the check fails. +- `err?` (`string`): Error message when the check fails. **Example**: @@ -476,9 +519,9 @@ ok, err = validate.string("hello") --> true, nil ok, err = validate.string(1) --> false, "string expected, got number" ``` - +--- -#### `table(v, msg?)` +#### `table(v, msg?)` {#table} Returns `true` when `v` is a table. Otherwise returns `false` and an error message. @@ -488,10 +531,10 @@ message. - `v` (`any`): Value to validate. - `msg?` (`string`): Optional override template. -**Return**: +**Returns**: - `isValid` (`boolean`): Whether the check succeeds. -- `err` (`string?`): Error message when the check fails. +- `err?` (`string`): Error message when the check fails. **Example**: @@ -500,9 +543,9 @@ ok, err = validate.table({}) --> true, nil ok, err = validate.table(1) --> false, "table expected, got number" ``` - +--- -#### `thread(v, msg?)` +#### `thread(v, msg?)` {#thread} Returns `true` when `v` is a thread. Otherwise returns `false` and an error message. @@ -512,10 +555,10 @@ message. - `v` (`any`): Value to validate. - `msg?` (`string`): Optional override template. -**Return**: +**Returns**: - `isValid` (`boolean`): Whether the check succeeds. -- `err` (`string?`): Error message when the check fails. +- `err?` (`string`): Error message when the check fails. **Example**: @@ -525,9 +568,9 @@ ok, err = validate.thread(co) --> true, nil ok, err = validate.thread(1) --> false, "thread expected, got number" ``` - +--- -#### `userdata(v, msg?)` +#### `userdata(v, msg?)` {#userdata} Returns `true` when `v` is a userdata value. Otherwise returns `false` and an error message. @@ -537,10 +580,10 @@ error message. - `v` (`any`): Value to validate. - `msg?` (`string`): Optional override template. -**Return**: +**Returns**: - `isValid` (`boolean`): Whether the check succeeds. -- `err` (`string?`): Error message when the check fails. +- `err?` (`string`): Error message when the check fails. **Example**: @@ -549,11 +592,11 @@ ok, err = validate.userdata(io.stdout) --> true, nil ok, err = validate.userdata(1) --> false, "userdata expected, got number" ``` -### Value Checks +--- - +### Value Checks -#### `callable(v, msg?)` +#### `callable(v, msg?)` {#callable} Returns `true` when `v` is callable. Otherwise returns `false` and an error message. @@ -563,10 +606,10 @@ message. - `v` (`any`): Value to validate. - `msg?` (`string`): Optional override template. -**Return**: +**Returns**: - `isValid` (`boolean`): Whether the check succeeds. -- `err` (`string?`): Error message when the check fails. +- `err?` (`string`): Error message when the check fails. **Example**: @@ -575,9 +618,9 @@ ok, err = validate.callable(type) --> true, nil ok, err = validate.callable(1) --> false, "callable value expected, got 1" ``` - +--- -#### `false(v, msg?)` +#### `false(v, msg?)` {#false} Returns `true` when `v` is exactly `false`. Otherwise returns `false` and an error message. @@ -587,10 +630,10 @@ error message. - `v` (`any`): Value to validate. - `msg?` (`string`): Optional override template. -**Return**: +**Returns**: - `isValid` (`boolean`): Whether the check succeeds. -- `err` (`string?`): Error message when the check fails. +- `err?` (`string`): Error message when the check fails. **Example**: @@ -599,9 +642,9 @@ ok, err = validate.False(false) --> true, nil ok, err = validate.False(true) --> false, "false value expected, got true" ``` - +--- -#### `falsy(v, msg?)` +#### `falsy(v, msg?)` {#falsy} Returns `true` when `v` is falsy. Otherwise returns `false` and an error message. @@ -611,10 +654,10 @@ message. - `v` (`any`): Value to validate. - `msg?` (`string`): Optional override template. -**Return**: +**Returns**: - `isValid` (`boolean`): Whether the check succeeds. -- `err` (`string?`): Error message when the check fails. +- `err?` (`string`): Error message when the check fails. **Example**: @@ -623,9 +666,9 @@ ok, err = validate.falsy(false) --> true, nil ok, err = validate.falsy(1) --> false, "falsy value expected, got 1" ``` - +--- -#### `integer(v, msg?)` +#### `integer(v, msg?)` {#integer} Returns `true` when `v` is an integer. Otherwise returns `false` and an error message. @@ -635,10 +678,10 @@ message. - `v` (`any`): Value to validate. - `msg?` (`string`): Optional override template. -**Return**: +**Returns**: - `isValid` (`boolean`): Whether the check succeeds. -- `err` (`string?`): Error message when the check fails. +- `err?` (`string`): Error message when the check fails. **Example**: @@ -647,9 +690,9 @@ ok, err = validate.integer(1) --> true, nil ok, err = validate.integer(1.5) --> false, "integer value expected, got 1.5" ``` - +--- -#### `true(v, msg?)` +#### `true(v, msg?)` {#true} Returns `true` when `v` is exactly `true`. Otherwise returns `false` and an error message. @@ -659,10 +702,10 @@ error message. - `v` (`any`): Value to validate. - `msg?` (`string`): Optional override template. -**Return**: +**Returns**: - `isValid` (`boolean`): Whether the check succeeds. -- `err` (`string?`): Error message when the check fails. +- `err?` (`string`): Error message when the check fails. **Example**: @@ -671,9 +714,9 @@ ok, err = validate.True(true) --> true, nil ok, err = validate.True(false) --> false, "true value expected, got false" ``` - +--- -#### `truthy(v, msg?)` +#### `truthy(v, msg?)` {#truthy} Returns `true` when `v` is truthy. Otherwise returns `false` and an error message. @@ -683,10 +726,10 @@ message. - `v` (`any`): Value to validate. - `msg?` (`string`): Optional override template. -**Return**: +**Returns**: - `isValid` (`boolean`): Whether the check succeeds. -- `err` (`string?`): Error message when the check fails. +- `err?` (`string`): Error message when the check fails. **Example**: @@ -695,51 +738,30 @@ ok, err = validate.truthy(1) --> true, nil ok, err = validate.truthy(false) --> false, "truthy value expected, got false" ``` -## Fields - - - -### `messages` (`modsValidatorMessages`) - -Custom error-message templates for validator failures. - -Set `validate.messages.`, where `` is a validator name (for example: -`number`, `truthy`, `file`). - -The error-message template is used only when validation fails and an error -message is returned. - -```lua -validate.messages.number = "need {{expected}}, got {{got}}" -ok, err = validate.number("x") --> false, "need number, got string" -``` - -**Placeholders**: - -- {{expected}}: The check target (for example `number`, - `string`, `truthy`). -- {{got}}: The detected failure kind (usually a Lua type; - path validators use `invalid path`). -- {{value}}: The passed value, formatted for display (strings - are quoted). - -> [!NOTE] -> -> When the passed value is `nil`, rendered value text uses `no value`. -> -> ```lua -> validate.messages.truthy = "{{expected}} value expected, got {{value}}" -> validate.truthy(nil) --> false, "truthy value expected, got no value" -> ``` - -**Default Messages**: - -- Type checks: {{expected}} expected, got {{got}} -- Value checks: {{expected}} value expected, got {{value}} -- Path checks: {{value}} is not a valid {{expected}} path - (for `path`: {{value}} is not a valid path) - -> [!NOTE] -> -> For path checks, if the value is not a `string`, the message falls back to -> `messages.string` (as if `validate.string` was called). + +[`block(v, msg?)`]: #block +[`boolean(v, msg?)`]: #boolean +[`callable(v, msg?)`]: #callable +[`char(v, msg?)`]: #char +[`device(v, msg?)`]: #device +[`dir(v, msg?)`]: #dir +[`false(v, msg?)`]: #false +[`falsy(v, msg?)`]: #falsy +[`fifo(v, msg?)`]: #fifo +[`file(v, msg?)`]: #file +[`function(v, msg?)`]: #function +[`integer(v, msg?)`]: #integer +[`lfs`]: https://github.com/lunarmodules/luafilesystem +[`link(v, msg?)`]: #link +[`nil(v, msg?)`]: #nil +[`number(v, msg?)`]: #number +[`path(v, msg?)`]: #path +[`register(name, validator, template?)`]: #register +[`socket(v, msg?)`]: #socket +[`string(v, msg?)`]: #string +[`table(v, msg?)`]: #table +[`thread(v, msg?)`]: #thread +[`true(v, msg?)`]: #true +[`truthy(v, msg?)`]: #truthy +[`userdata(v, msg?)`]: #userdata + diff --git a/docs/types.md b/docs/types.md new file mode 100644 index 0000000..5bbfbe4 --- /dev/null +++ b/docs/types.md @@ -0,0 +1,306 @@ +--- +title: "Types" +description: "Types defined in the mods module." +--- + +Types defined in the mods module. + +## [`mods.CalendarMonth`](https://github.com/BlueLua/mods/blob/main/types/calendar.d.lua#L12-L25) + +| Value | Description | +| ----- | ----------- | +| `1` | January | +| `2` | February | +| `3` | March | +| `4` | April | +| `5` | May | +| `6` | June | +| `7` | July | +| `8` | August | +| `9` | September | +| `10` | October | +| `11` | November | +| `12` | December | + +## [`mods.CalendarWeekday`](https://github.com/BlueLua/mods/blob/main/types/calendar.d.lua#L3-L11) + +| Value | Description | +| ----- | ----------- | +| `1` | Monday | +| `2` | Tuesday | +| `3` | Wednesday | +| `4` | Thursday | +| `5` | Friday | +| `6` | Saturday | +| `7` | Sunday | + +## [`mods.dateMod`](https://github.com/BlueLua/mods/blob/main/types/date.d.lua#L6-L62) + +Timezone-naive date helpers and immutable date values. + +## Usage + +```lua +local Date = require "mods.date" + +local a = Date("2026-03-30T14:45:06") +local b = Date("2026-03-30 14:45:06.123") +local c = Date("2026-03-31") +local d = Date("12-25-1995", "MM-DD-YYYY") +local e = Date({ year = 2026, month = 3, day = 30, hour = 14, min = 45 }) +local f = Date({ year = 2026 }) + +print(a) --> 2026-03-30 14:45:06 +print(b.ms) --> 123 +print(a:format("YYYY/MM/DD HH:mm:ss")) --> 2026/03/30 14:45:06 +print(a:is_before(c)) --> true +print(a < c) --> true +print(d) --> 1995-12-25 00:00:00 +print(e.sec) --> 0 +print(f) --> 2026-01-01 00:00:00 +``` + +> [!NOTE] +> +> - String inputs accept [ISO 8601] forms, variants using a space instead of +> `T`, and custom formats via `Date(input, pattern)`: +> +> ```lua +> Date("2026-03-30T14:45:06") +> Date("2026-03-30 14:45:06") +> Date("12/25/1995", "MM/DD/YYYY") +> ``` +> +> - When `input` is a number, it is treated as Unix milliseconds. Use +> [`Date.unix(ts)`] if you have a timestamp in seconds. +> +> ```lua +> local a = Date(1745155206123) -- Milliseconds +> local b = Date.unix(1745155206.123) -- Seconds +> print(a == b) --> true +> ``` +> +> - When calling `Date` without arguments, it uses [mstime] for millisecond +> precision if installed; otherwise it falls back to [`os.time`]. + +| Field | Type | Optional | Description | +| ---------- | -------------------- | -------- | ------------------ | +| `duration` | [`mods.durationMod`] | No | +| `private` | `__call` | No | fun(...):mods.Date | + +## [`mods.DateParts`](https://github.com/BlueLua/mods/blob/main/types/date.d.lua#L3-L5) + +| Field | Type | Optional | +| ------- | --------- | -------- | +| `day` | `integer` | Yes | +| `hour` | `integer` | Yes | +| `isdst` | `boolean` | Yes | +| `min` | `integer` | Yes | +| `month` | `integer` | Yes | +| `ms` | `integer` | Yes | +| `sec` | `integer` | Yes | +| `wday` | `integer` | Yes | +| `yday` | `integer` | Yes | +| `year` | `integer` | No | + +## [`mods.DateUnit`](https://github.com/BlueLua/mods/blob/main/types/date.d.lua#L3-L5) + + `"d"`  `"day"`  `"days"`  `"h"`  `"hour"` + `"hours"`  `"M"`  `"m"`  `"millisecond"` + `"milliseconds"`  `"min"`  `"mins"`  `"minute"` + `"minutes"`  `"month"`  `"months"`  `"ms"`  `"q"` + `"quarter"`  `"quarters"`  `"s"`  `"sec"`  `"second"` + `"seconds"`  `"secs"`  `"w"`  `"week"`  `"weeks"` + `"y"`  `"year"`  `"years"` + +## [`mods.DurationHumanizeOptions`](https://github.com/BlueLua/mods/blob/main/types/duration.d.lua#L6-L12) + +| Field | Type | Optional | Description | +| ------------- | ---------------------------------- | -------- | ------------------------------------------------------- | +| `max_unit` | [`mods.DateUnit`] | Yes | Largest unit allowed when choosing the displayed unit. | +| `min_unit` | [`mods.DateUnit`] | Yes | Smallest unit allowed when choosing the displayed unit. | +| `round` | [`mods.DurationHumanizeRoundMode`] | Yes | Rounding mode for custom unit output. | +| `short` | `boolean` | Yes | Whether to use abbreviated unit labels like `2h`. | +| `with_suffix` | `boolean` | Yes | Whether to include `ago` / `in` style wording. | + +## [`mods.DurationHumanizeRoundMode`](https://github.com/BlueLua/mods/blob/main/types/duration.d.lua#L3-L5) + + `"ceil"`  `"floor"`  `"round"`  `boolean` + +## [`mods.DurationParts`](https://github.com/BlueLua/mods/blob/main/types/duration.d.lua#L3-L5) + +| Field | Type | Optional | +| -------------- | -------- | -------- | +| `days` | `number` | Yes | +| `hours` | `number` | Yes | +| `milliseconds` | `number` | Yes | +| `minutes` | `number` | Yes | +| `months` | `number` | Yes | +| `quarters` | `number` | Yes | +| `seconds` | `number` | Yes | +| `weeks` | `number` | Yes | +| `years` | `number` | Yes | + +## [`mods.FsEntryType`](https://github.com/BlueLua/mods/blob/main/types/fs.d.lua#L3-L12) + +| Value | Description | +| ------------- | ------------------------------------- | +| `"block"` | A block device. | +| `"char"` | A character device. | +| `"directory"` | A directory. | +| `"fifo"` | A named pipe (FIFO). | +| `"file"` | A regular file. | +| `"link"` | A symbolic link. | +| `"socket"` | A socket. | +| `"unknown"` | An unknown or unsupported entry type. | + +## [`mods.GlobOptions`](https://github.com/BlueLua/mods/blob/main/types/glob.d.lua#L3-L4) + +| Field | Type | Optional | +| ------------ | --------- | -------- | +| `follow` | `boolean` | Yes | +| `hidden` | `boolean` | Yes | +| `ignorecase` | `boolean` | Yes | +| `recursive` | `boolean` | Yes | + +## [`mods.log.levelno`](https://github.com/BlueLua/mods/blob/main/types/log.d.lua#L13-L20) + +| Name | Value | +| ------- | ------------- | +| `debug` | `10` | +| `error` | `40` | +| `info` | `20` | +| `off` | `"math.huge"` | +| `warn` | `30` | + +## [`mods.log.new.opts`](https://github.com/BlueLua/mods/blob/main/types/log.d.lua#L30-L34) + +| Field | Type | Optional | Description | +| --------- | ------------------- | -------- | ---------------------------------------------------------------------------- | +| `handler` | [`mods.LogHandler`] | Yes | Optional handler function that receives each emitted record. | +| `level` | [`mods.LogLevel`] | Yes | Minimum enabled level; use `"off"` to disable logging. Defaults to `"warn"`. | +| `name` | `string` | Yes | Optional logger name included in emitted records. | + +## [`mods.log.record`](https://github.com/BlueLua/mods/blob/main/types/log.d.lua#L22-L29) + +| Field | Type | Optional | Description | +| ----------- | ---------------------------- | -------- | ------------------------------------ | +| `args` | `{[integer]:any, n:integer}` | No | Original variadic arguments. | +| `levelname` | [`mods.LogLevel`] | No | Log level name. | +| `levelno` | `integer` | No | Numeric severity used for filtering. | +| `line` | `string` | No | Formatted plain-text log line. | +| `message` | `string` | No | Joined message string. | + +## [`mods.LogHandler`](https://github.com/BlueLua/mods/blob/main/types/log.d.lua#L11-L12) + +`fun(record: mods.log.record)` + +## [`mods.LogLevel`](https://github.com/BlueLua/mods/blob/main/types/log.d.lua#L3-L10) + +| Value | Description | +| --------- | -------------------------- | +| `"debug"` | Debug messages. | +| `"error"` | Error messages. | +| `"info"` | Informational messages. | +| `"off"` | Logging disabled. | +| `"warn"` | Warning messages. | +| `string` | Any custom log level name. | + +## [`mods.modsCalendarMonthday`](https://github.com/BlueLua/mods/blob/main/types/calendar.d.lua#L26-L58) + +| Value | Description | +| ----- | --------------------- | +| `1` | 1st day of the month | +| `2` | 2nd day of the month | +| `3` | 3rd day of the month | +| `4` | 4th day of the month | +| `5` | 5th day of the month | +| `6` | 6th day of the month | +| `7` | 7th day of the month | +| `8` | 8th day of the month | +| `9` | 9th day of the month | +| `10` | 10th day of the month | +| `11` | 11th day of the month | +| `12` | 12th day of the month | +| `13` | 13th day of the month | +| `14` | 14th day of the month | +| `15` | 15th day of the month | +| `16` | 16th day of the month | +| `17` | 17th day of the month | +| `18` | 18th day of the month | +| `19` | 19th day of the month | +| `20` | 20th day of the month | +| `21` | 21st day of the month | +| `22` | 22nd day of the month | +| `23` | 23rd day of the month | +| `24` | 24th day of the month | +| `25` | 25th day of the month | +| `26` | 26th day of the month | +| `27` | 27th day of the month | +| `28` | 28th day of the month | +| `29` | 29th day of the month | +| `30` | 30th day of the month | +| `31` | 31st day of the month | + +## [`mods.ValidatorName`](https://github.com/BlueLua/mods/blob/main/types/is.d.lua#L6-L24) + +| Value | Description | +| ------------ | --------------------------------------------------------- | +| `"block"` | A block device path. | +| `"callable"` | A function or table with a `__call` metamethod. | +| `"char"` | A character device path. | +| `"device"` | A character or block device path. | +| `"dir"` | A directory path. | +| `"false"` | The boolean value false. | +| `"falsy"` | A falsy value (nil or false). | +| `"fifo"` | A named pipe (FIFO) path. | +| `"file"` | A regular file path. | +| `"integer"` | An integer number. | +| `"link"` | A symbolic link path. | +| `"path"` | Any existing path or symbolic link. | +| `"socket"` | A socket path. | +| `"true"` | The boolean value true. | +| `"truthy"` | A truthy value (not nil and not false). | +| `string` | Any validator name. | +| `type` | Any standard Lua type name (e.g., `"table"`, `"number"`). | + +## [`modsValidatorMessages`](https://github.com/BlueLua/mods/blob/main/types/validate.d.lua#L3-L31) + +| Field | Type | Optional | +| ---------- | -------- | -------- | +| `[string]` | `string` | No | +| `block` | `string` | Yes | +| `boolean` | `string` | Yes | +| `callable` | `string` | Yes | +| `char` | `string` | Yes | +| `device` | `string` | Yes | +| `dir` | `string` | Yes | +| `false` | `string` | Yes | +| `falsy` | `string` | Yes | +| `fifo` | `string` | Yes | +| `file` | `string` | Yes | +| `function` | `string` | Yes | +| `integer` | `string` | Yes | +| `link` | `string` | Yes | +| `nil` | `string` | Yes | +| `number` | `string` | Yes | +| `path` | `string` | Yes | +| `socket` | `string` | Yes | +| `string` | `string` | Yes | +| `table` | `string` | Yes | +| `thread` | `string` | Yes | +| `true` | `string` | Yes | +| `truthy` | `string` | Yes | +| `userdata` | `string` | Yes | + + +[ISO 8601]: https://en.wikipedia.org/wiki/ISO_8601 +[`Date.unix(ts)`]: #fn-unix +[`mods.DateUnit`]: /mods/types#mods-dateunit +[`mods.DurationHumanizeRoundMode`]: /mods/types#mods-durationhumanizeroundmode +[`mods.LogHandler`]: /mods/types#mods-loghandler +[`mods.LogLevel`]: /mods/types#mods-loglevel +[`mods.durationMod`]: /mods/types#mods-durationmod +[`os.time`]: https://www.lua.org/manual/5.1/manual.html#pdf-os.time +[mstime]: https://github.com/luamod/mstime +