mirror of
https://github.com/MihailRis/voxelcore.git
synced 2026-10-04 10:31:50 +00:00
update scripting docs
This commit is contained in:
parent
c3794191e2
commit
da6a36a76c
4 changed files with 107 additions and 6 deletions
|
|
@ -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.
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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 вернёт кешированный результат.
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
# Свойства и методы UI элементов
|
||||
|
||||
Обращение к UI элементов в скриптах произодится через экземпляр Document
|
||||
(переменная document) по id, указанному в xml.
|
||||
(глобальная переменная document) по id, указанному в xml.
|
||||
|
||||
Пример: вывод в консоль свойства pos элемента с id: "worlds-panel":
|
||||
```lua
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue