Merge pull request #878 from MihailRis/suggested-functions

small suggested functions
This commit is contained in:
MihailRis 2026-07-22 01:00:13 +03:00 • committed by GitHub
commit 5284d4acaa
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
13 changed files with 164 additions and 12 deletions

View file

@ -60,13 +60,18 @@ Property used via [inventory.use](scripting/builtins/libinventory.md).
Property status is displayed in the inventory interface. Display method is defined via `uses-display`.
### Display of uses - `uses-display`
### Display of remaining uses count - `uses-display`
- `none` - display disabled
- `number` - number
- `relation` - current value to initial value (x/y)
- `vbar` - vertical scale (used by default)
### *script-name*
Defines the name of the script containing the item's event handlers. By default, equals to the item's string id (name).
Allows you to reuse a single script for multiple items.
## Tags
Tags allow you to designate general properties of items. Names should be formatted as `prefix:tag_name`.

View file

@ -58,9 +58,58 @@ not part of Lua syntax.
- quat - array of four numbers - quaternion
- matrix - array of 16 numbers - matrix
## Core functions
## Namespaces
Currently, the engine uses a namespace hierarchy that minimizes conflicts between individual modules, scripts, and even packs.
The following structure is relevant:
- Global namespace (_G), which is the root namespace. Writing to it outside of engine core modules is highly undesirable, as it can waste hours of debugging time.
- Pack namespace - created each time content is loaded for each pack included in the configuration. This namespace is used by modules, as well as item and block scripts.
- [Component namespace](scripting/ecs.md#built-in-components).
- [UI document namespace](scripting/ui.md).
- Isolated world generator namespace.
## Modules
A module is a global object with a lifetime limited to the lifetime of the loaded content, used both for interaction between different packages and as a substitute for global variables within the package itself.
The module must be located in `contentpack/modules/**` (subfolders are allowed, but you will need to specify them)
```lua
require "packid:module_name" -- load Lua module from pack-folder/modules/
-- no extension included, just name
local module_name = require "contentpack:module_name" -- imports the module
-- If the module is in the same pack in which it is imported, you can use the shortcut:
local module_name = require "module_name"
-- When using nested folders:
local module_name = require "contentpack:path/to/module_name" -- the path does not include `modules`
local module_name = require "path/to/module_name" -- if in the same pack
```
The module will have the namespace of the folder in which it is located, regardless of the namespace from which the first import was performed.
When creating a module, you should follow the following approach, which is what *require* expects:
```lua
local this = {
variable_name = ... -- public variables
}
-- private module variables
local variable_name = ...
-- private module functions
local function function_name(...)
...
end
-- public module functions
function this.function_name(...)
...
end
return this -- the result that require will return and cache
```
When reimported, the module will not be reloaded; instead, require will return the cached result.

View file

@ -30,6 +30,9 @@ entities.def_hitbox(id: int) -> vec3
-- Returns entity definition name by index (string ID).
entities.def_name(id: int) -> str
-- Returns true if the entity is a solid obstacle.
entities.def_solid(id: int) -> boolean
-- Returns entity definition index by name (integer ID).
entities.def_index(name: str) -> int
@ -51,12 +54,12 @@ entities.get_all() -> table
-- Returns a table of loaded entities based on the passed list of UIDs
entities.get_all(uids: array<int>) -> table
-- Returns a list of UIDs of entities inside the rectangular area
-- Returns a list of UIDs of entities with origin inside the rectangular area
-- pos - minimal area corner
-- size - area size
entities.get_all_in_box(pos: vec3, size: vec3) -> array<int>
-- Returns a list of UIDs of entities inside the radius
-- Returns a list of UIDs of entities with origin inside the radius
-- center - center of the area
-- radius - radius of the area
entities.get_all_in_radius(center: vec3, radius: number) -> array<int>

View file

@ -38,6 +38,17 @@ entity:set_enabled(name: str, enable: bool)
entity:get_player() -> int or nil
```
## Custom Components
A component is defined as a script in `{pack}/scripts/components/{name}.lua`.
The component will be available for use in the entity definition as `{pack}:{name}`.
Example: `core:scripts/components/pathfinding.lua` -> `core:pathfinding`.
For **each** entity containing a component, a **separate instance** is created with **its own namespace** within the pack namespace.
Global variables declared in it act as public fields of the component (same for global functions).
Entity components are specified via the ["components" list](../entity-properties.md#components)
## Built-in components
### Transform

View file

@ -1,7 +1,7 @@
# UI properties and methods
UI elements in scripts are accessed through a Document instance
(*document* variable) by id specified in xml.
(global *document* variable) by id specified in xml.
Example: print the pos property of an element with id: "worlds-panel" to the console:
```lua

View file

@ -66,6 +66,10 @@
- `relation` - отношение текущего значения к изначальному (x/y)
- `vbar` - вертикальная шкала (используется по-умолчанию)
### Имя скрипта - `script-name`
Определяет имя скрипта, содержащего обработчики событий предмета. По-умолчанию соответствует строковому id (имени) предмета.
Свойство обеспечивает возможность использования одного скрипта для нескольких предметов.
## Теги - *tags*

View file

@ -60,6 +60,58 @@
- quat - массив из четырех чисел - кватернион
- matrix - массив из 16 чисел - матрица
## Пространства имён
В настоящее время, движок использует иерархию пространств имён, минимизирующую конфликты между отдельными модулями, скриптами, да и паками.
Актуальна следующая структура:
- Глобальное пространство (оно же - _G), являющееся корневым, запись в которое, вне модулей ядра движка, является крайне нежелательным для вашего же времени, что может уйти на лишние часы отладки.
- Пространство пака - создаётся каждый раз при загрузке контента для каждого, включённого в конфигурацию, пака. Это пространство используют модули, а также скрипты предметов и блоков.
- Пространство [компонента](scripting/ecs.md#пользовательские-компоненты).
- Пространство [UI-документа](scripting/ui.md)
- Изолированное пространство имён генератора мира.
## Модули
Модуль - глобальный объект со сроком жизни, ограниченным сроком жизни контента, используемый как для взаимодействия разных паков, так и для вместо глобальных переменных в пределах самого пака.
Модуль должен находиться в `контентпак/modules/**` (допускаются вложенные папки, что нужно будет указывать)
```lua
require "контентпак:имя_модуля" -- загружает lua модуль из папки modules (расширение не указывается)
local имя_модуля = require "контентпак:имя_модуля" -- импортирует модуль
-- если модуль находится в том же паке, в котором импортируется, можно использовать сокращённый вариант:
local имя_модуля = require "имя_модуля"
-- при использовании вложенных папок:
local имя_модуля = require "контентпак:путь/к/имя_модуля" -- путь не включает `modules`
local имя_модуля = require "путь/к/имя_модуля" -- если в том же паке
```
Модуль будет иметь пространство имён того пака, в котором находится, независимо от пространства имён, из которого был выполнен первый импорт.
При создании модуля следует придерживаться следующего подхода, которого и ожидает *require*:
```lua
local this = {
имя_переменной = ... -- публичные переменные
}
-- приватные переменные модуля
local имя_переменной = ...
-- приватные функции модуля
local function имя_функции(...)
...
end
-- публичные функции модуля
function this.имя_функции(...)
...
end
return this -- результат, который и будет возвращать и кешировать require
```
При повторном импорте модуль не будет перезагружен - вместо этого require вернёт кешированный результат.

View file

@ -30,6 +30,9 @@ entities.def_name(id: int) -> string
-- Возвращает значение свойства 'hitbox' сущности
entities.def_hitbox(id: int) -> vec3
-- Возвращает true если сущность является осязаемым препятствием.
entities.def_solid(id: int) -> boolean
-- Возвращает индекс определения сущности по имени (числовой ID).
entities.def_index(name: string) -> int
@ -50,12 +53,12 @@ entities.get_all() -> table
-- Возвращает таблицу загруженных сущностей по переданному списку UID
entities.get_all(uids: table<int>) -> table
-- Возвращает список UID сущностей, попадающих в прямоугольную область
-- Возвращает список UID сущностей, позиции которых попадают в прямоугольную область
-- pos - минимальный угол области
-- size - размер области
entities.get_all_in_box(pos: vec3, size: vec3) -> table<int>
-- Возвращает список UID сущностей, попадающих в радиус
-- Возвращает список UID сущностей, позиции которых попадают в радиус
-- center - центр области
-- radius - радиус области
entities.get_all_in_radius(center: vec3, radius: number) -> table<int>

View file

@ -180,6 +180,17 @@ rig:get_color() -> vec3
rig:set_color(color: vec3)
```
## Пользовательские компоненты
Компонент описывается в виде скрипта `{пак}/scripts/components/{имя}.lua`.
Компонент будет доступен для использования в описании сущности как `{пак}:{имя}`.
Пример: `core:scripts/components/pathfinding.lua` -> `core:pathfinding`.
Для **каждой** сущности, содержащей компонент, создаётся **отдельный экземпляр** со **своим пространством имен** внутри пространства имён пака.
Глобальные переменные, объявляемые в нём, играют роль публичных полей компонента (как и глобальные функции).
Компоненты сущности указываются через [список "components"](../entity-properties.md#cписок-компонентов---components)
> [!WARNING]
> При выходе сущности за пределы зоны прогрузки она удаляется, вызывая события.
> При повторном попадании в зону прогрузки сущность спавнится заново.

View file

@ -156,6 +156,8 @@ math.round(num: number, [опционально] places: number) -> number
-- Возвращает сумму всех принимаемых аргументов. Если в качестве аргумента была передана таблица, метод вернёт сумму всех её элементов.
math.sum(x: number, ... | t: table) -> number
-- Возвращает целое число, указывающее знак числа (-1/0/1)
math.sign(x: number) -> int
```
## Расширения для bit
@ -200,4 +202,4 @@ await(co: coroutine) -> result, error
-- Константа, в которой хранится PID текущего инстанса движка.
os.pid -> number
```
```

View file

@ -1,7 +1,7 @@
# Свойства и методы UI элементов
Обращение к UI элементов в скриптах произодится через экземпляр Document
(переменная document) по id, указанному в xml.
(глобальная переменная document) по id, указанному в xml.
Пример: вывод в консоль свойства pos элемента с id: "worlds-panel":
```lua

View file

@ -35,3 +35,7 @@ function math.sum(...)
return sum
end
function math.sign(x)
return (x > 0) and 1 or (x < 0 and -1 or 0)
end

View file

@ -50,6 +50,13 @@ static int l_def_hitbox(lua::State* L) {
return 0;
}
static int l_def_solid(lua::State* L) {
if (auto def = require_entity_def(L)) {
return lua::pushboolean(L, def->solid);
}
return 0;
}
static int l_defs_count(lua::State* L) {
return lua::pushinteger(L, indices->entities.count());
}
@ -373,6 +380,7 @@ const luaL_Reg entitylib[] = {
{"def_index", lua::wrap<l_def_index>},
{"def_name", lua::wrap<l_def_name>},
{"def_hitbox", lua::wrap<l_def_hitbox>},
{"def_solid", lua::wrap<l_def_solid>},
{"get_def", lua::wrap<l_get_def>},
{"defs_count", lua::wrap<l_defs_count>},
{"spawn", lua::wrap<l_spawn>},