add file.read_combined_object & update filesystem docs

This commit is contained in:
MihailRis 2024-11-05 14:33:56 +03:00
parent 6f2f365278
commit 4932fd8b4b
7 changed files with 283 additions and 200 deletions

View File

@ -12,6 +12,7 @@ Subsections:
- [block](scripting/builtins/libblock.md)
- [cameras](scripting/builtins/libcameras.md)
- [entities](scripting/builtins/libentities.md)
- [file](scripting/builtins/libfile.md)
- [gui](scripting/builtins/libgui.md)
- [hud](scripting/builtins/libhud.md)
- [inventory](scripting/builtins/libinventory.md)

View File

@ -0,0 +1,116 @@
# *file* library
Filesystem interaction library.
```python
file.resolve(path: str) -> str
```
Function turns `entry_point:path` (example `user:worlds/house1`) to a regular path. (example `C://Users/user/.voxeng/worlds/house1`)
> [!NOTE]
> The function should be used for debug only. *entry_point:path* notation is required in all **file** functions.
Resulting path is not canonical and may be relative.
```python
file.read(path: str) -> str
```
Read whole text file.
```python
file.read_bytes(path: str) -> array of integers
```
Read file into bytes array.
```python
file.write(path: str, text: str) -> nil
```
Overwrite text file.
```python
file.write_bytes(path: str, data: array of integers)
```
Overwrite binary file with bytes array.
```python
file.length(path: str) -> int
```
Get file length (bytes) or 0.
```python
file.exists(path: str) -> bool
```
Check if file or directory exist.
```python
file.isfile(path: str) -> bool
```
Check if the path points to a file.
```python
file.isdir(path: str) -> bool
```
Check if the path points to a directory.
```python
file.mkdir(path: str) -> bool
```
Create directory. Returns true if new directory created
```python
file.mkdirs(path: str) -> bool
```
Create directories chain. Returns true if new directory created.
```python
file.list(path: str) -> array of strings
```
Returns a list of files and directories in the specified.
```python
file.list_all_res(path: str) -> array of strings
```
Returns a list of files and directories in the specified one without specifying an entry point.
```python
file.find(path: str) -> str
```
Searches for a file from the last pack to res. The path is specified without a prefix. Returns the path with the required prefix. If the file is not found, returns nil.
```python
file.remove(path: str) -> bool
```
Deletes a file. Returns **true** if the file exists. Throws an exception on access violation.
```python
file.remove_tree(path: str) -> int
```
Recursively deletes files. Returns the number of files deleted.
```python
file.read_combined_list(path: str) -> array
```
Combines arrays from JSON files of different packs.
```python
file.read_combined_object(path: str) -> array
```
Combines objects from JSON files of different packs.

View File

@ -2,78 +2,7 @@
### *file* library
Filesystem interaction library.
```python
file.resolve(path: str) -> str
```
Function turns `entry_point:path` (example `user:worlds/house1`) to a regular path. (example `C://Users/user/.voxeng/worlds/house1`)
> [!NOTE]
> The function should be used for debug only. *entry_point:path* notation is required in all **file** functions.
Resulting path is not canonical and may be relative.
```python
file.read(path: str) -> str
```
Read whole text file.
```python
file.read_bytes(path: str) -> array of integers
```
Read file into bytes array.
```python
file.write(path: str, text: str) -> nil
```
Overwrite text file.
```python
file.write_bytes(path: str, data: array of integers)
```
Overwrite binary file with bytes array.
```python
file.length(path: str) -> int
```
Get file length (bytes) or 0.
```python
file.exists(path: str) -> bool
```
Check if file or directory exist.
```python
file.isfile(path: str) -> bool
```
Check if the path points to a file.
```python
file.isdir(path: str) -> bool
```
Check if the path points to a directory.
```python
file.mkdir(path: str) -> bool
```
Create directory. Returns true if new directory created
```python
file.mkdirs(path: str) -> bool
```
Create directories chain. Returns true if new directory created.
See [file library](builtins/libfile.md)
## *json* library

View File

@ -12,6 +12,7 @@
- [block](scripting/builtins/libblock.md)
- [cameras](scripting/builtins/libcameras.md)
- [entities](scripting/builtins/libentities.md)
- [file](scripting/builtins/libfile.md)
- [gui](scripting/builtins/libgui.md)
- [hud](scripting/builtins/libhud.md)
- [inventory](scripting/builtins/libinventory.md)

View File

@ -0,0 +1,116 @@
# Библиотека *file*
Библиотека функций для работы с файлами
```python
file.resolve(путь: str) -> str
```
Функция приводит запись очкахода:путь` (например `user:worlds/house1`) к обычному пути. (например `C://Users/user/.voxeng/worlds/house1`)
> [!NOTE]
> Функцию не нужно использовать в сочетании с другими функциями из библиотеки, так как они делают это автоматически
Возвращаемый путь не является каноническим и может быть как абсолютным, так и относительным.
```python
file.read(путь: str) -> str
```
Читает весь текстовый файл и возвращает в виде строки
```python
file.read_bytes(путь: str) -> array of integers
```
Читает файл в массив байт.
```python
file.write(путь: str, текст: str) -> nil
```
Записывает текст в файл (с перезаписью)
```python
file.write_bytes(путь: str, data: array of integers)
```
Записывает массив байт в файл (с перезаписью)
```python
file.length(путь: str) -> int
```
Возвращает размер файла в байтах, либо -1, если файл не найден
```python
file.exists(путь: str) -> bool
```
Проверяет, существует ли по данному пути файл или директория
```python
file.isfile(путь: str) -> bool
```
Проверяет, существует ли по данному пути файл
```python
file.isdir(путь: str) -> bool
```
Проверяет, существует ли по данному пути директория
```python
file.mkdir(путь: str) -> bool
```
Создает директорию. Возвращает true если была создана новая директория
```python
file.mkdirs(путь: str) -> bool
```
Создает всю цепочку директорий. Возвращает true если были созданы директории.
```python
file.list(путь: str) -> массив строк
```
Возвращает список файлов и директорий в указанной.
```python
file.list_all_res(путь: str) -> массив строк
```
Возвращает список файлов и директорий в указанной без указания конкретной точки входа.
```python
file.find(путь: str) -> str
```
Ищет файл от последнего пака до res. Путь указывается без префикса. Возвращает путь с нужным префиксом. Если файл не найден, возвращает nil.
```python
file.remove(путь: str) -> bool
```
Удаляет файл. Возращает **true** если файл существовал. Бросает исключение при нарушении доступа.
```python
file.remove_tree(путь: str) -> int
```
Рекурсивно удаляет файлы. Возвращает число удаленных файлов.
```python
file.read_combined_list(путь: str) -> массив
```
Совмещает массивы из JSON файлов разных паков.
```python
file.read_combined_object(путь: str) -> массив
```
Совмещает объекты из JSON файлов разных паков.

View File

@ -2,96 +2,7 @@
## Библиотека *file*
Библиотека функций для работы с файлами
```python
file.resolve(путь: str) -> str
```
Функция приводит запись очкахода:путь` (например `user:worlds/house1`) к обычному пути. (например `C://Users/user/.voxeng/worlds/house1`)
> [!NOTE]
> Функцию не нужно использовать в сочетании с другими функциями из библиотеки, так как они делают это автоматически
Возвращаемый путь не является каноническим и может быть как абсолютным, так и относительным.
```python
file.read(путь: str) -> str
```
Читает весь текстовый файл и возвращает в виде строки
```python
file.read_bytes(путь: str) -> array of integers
```
Читает файл в массив байт.
```python
file.write(путь: str, текст: str) -> nil
```
Записывает текст в файл (с перезаписью)
```python
file.write_bytes(путь: str, data: array of integers)
```
Записывает массив байт в файл (с перезаписью)
```python
file.length(путь: str) -> int
```
Возвращает размер файла в байтах, либо -1, если файл не найден
```python
file.exists(путь: str) -> bool
```
Проверяет, существует ли по данному пути файл или директория
```python
file.isfile(путь: str) -> bool
```
Проверяет, существует ли по данному пути файл
```python
file.isdir(путь: str) -> bool
```
Проверяет, существует ли по данному пути директория
```python
file.mkdir(путь: str) -> bool
```
Создает директорию. Возвращает true если была создана новая директория
```python
file.mkdirs(путь: str) -> bool
```
Создает всю цепочку директорий. Возвращает true если были созданы директории.
```python
file.find(путь: str) -> str
```
Ищет файл от последнего пака до res. Путь указывается без префикса. Возвращает путь с нужным префиксом. Если файл не найден, возвращает nil.
```python
file.remove(путь: str) -> bool
```
Удаляет файл. Возращает **true** если файл существовал. Бросает исключение при нарушении доступа.
```python
file.remove_tree(путь: str) -> int
```
Рекурсивно удаляет файлы. Возвращает число удаленных файлов.
См. [библиотека file](builtins/libfile.md)
## Библиотека json

View File

@ -23,7 +23,7 @@ static fs::path resolve_path_soft(const std::string& path) {
return engine->getPaths()->resolve(path, false);
}
static int l_file_find(lua::State* L) {
static int l_find(lua::State* L) {
auto path = lua::require_string(L, 1);
try {
return lua::pushstring(L, engine->getResPaths()->findRaw(path));
@ -32,12 +32,12 @@ static int l_file_find(lua::State* L) {
}
}
static int l_file_resolve(lua::State* L) {
static int l_resolve(lua::State* L) {
fs::path path = resolve_path(lua::require_string(L, 1));
return lua::pushstring(L, path.u8string());
}
static int l_file_read(lua::State* L) {
static int l_read(lua::State* L) {
fs::path path = resolve_path(lua::require_string(L, 1));
if (fs::is_regular_file(path)) {
return lua::pushstring(L, files::read_string(path));
@ -47,7 +47,7 @@ static int l_file_read(lua::State* L) {
);
}
static int l_file_write(lua::State* L) {
static int l_write(lua::State* L) {
fs::path path = resolve_path(lua::require_string(L, 1));
std::string text = lua::require_string(L, 2);
files::write_string(path, text);
@ -58,7 +58,7 @@ static std::set<std::string> writeable_entry_points {
"world", "export", "config"
};
static int l_file_remove(lua::State* L) {
static int l_remove(lua::State* L) {
std::string rawpath = lua::require_string(L, 1);
fs::path path = resolve_path(rawpath);
auto entryPoint = rawpath.substr(0, rawpath.find(':'));
@ -68,7 +68,7 @@ static int l_file_remove(lua::State* L) {
return lua::pushboolean(L, fs::remove(path));
}
static int l_file_remove_tree(lua::State* L) {
static int l_remove_tree(lua::State* L) {
std::string rawpath = lua::require_string(L, 1);
fs::path path = resolve_path(rawpath);
auto entryPoint = rawpath.substr(0, rawpath.find(':'));
@ -78,22 +78,22 @@ static int l_file_remove_tree(lua::State* L) {
return lua::pushinteger(L, fs::remove_all(path));
}
static int l_file_exists(lua::State* L) {
static int l_exists(lua::State* L) {
fs::path path = resolve_path_soft(lua::require_string(L, 1));
return lua::pushboolean(L, fs::exists(path));
}
static int l_file_isfile(lua::State* L) {
static int l_isfile(lua::State* L) {
fs::path path = resolve_path_soft(lua::require_string(L, 1));
return lua::pushboolean(L, fs::is_regular_file(path));
}
static int l_file_isdir(lua::State* L) {
static int l_isdir(lua::State* L) {
fs::path path = resolve_path_soft(lua::require_string(L, 1));
return lua::pushboolean(L, fs::is_directory(path));
}
static int l_file_length(lua::State* L) {
static int l_length(lua::State* L) {
fs::path path = resolve_path(lua::require_string(L, 1));
if (fs::exists(path)) {
return lua::pushinteger(L, fs::file_size(path));
@ -102,17 +102,17 @@ static int l_file_length(lua::State* L) {
}
}
static int l_file_mkdir(lua::State* L) {
static int l_mkdir(lua::State* L) {
fs::path path = resolve_path(lua::require_string(L, 1));
return lua::pushboolean(L, fs::create_directory(path));
}
static int l_file_mkdirs(lua::State* L) {
static int l_mkdirs(lua::State* L) {
fs::path path = resolve_path(lua::require_string(L, 1));
return lua::pushboolean(L, fs::create_directories(path));
}
static int l_file_read_bytes(lua::State* L) {
static int l_read_bytes(lua::State* L) {
fs::path path = resolve_path(lua::require_string(L, 1));
if (fs::is_regular_file(path)) {
size_t length = static_cast<size_t>(fs::file_size(path));
@ -154,7 +154,7 @@ static int read_bytes_from_table(
}
}
static int l_file_write_bytes(lua::State* L) {
static int l_write_bytes(lua::State* L) {
int pathIndex = 1;
if (!lua::isstring(L, pathIndex)) {
@ -181,7 +181,7 @@ static int l_file_write_bytes(lua::State* L) {
}
}
static int l_file_list_all_res(lua::State* L, const std::string& path) {
static int l_list_all_res(lua::State* L, const std::string& path) {
auto files = engine->getResPaths()->listdirRaw(path);
lua::createtable(L, files.size(), 0);
for (size_t i = 0; i < files.size(); i++) {
@ -191,10 +191,10 @@ static int l_file_list_all_res(lua::State* L, const std::string& path) {
return 1;
}
static int l_file_list(lua::State* L) {
static int l_list(lua::State* L) {
std::string dirname = lua::require_string(L, 1);
if (dirname.find(':') == std::string::npos) {
return l_file_list_all_res(L, dirname);
return l_list_all_res(L, dirname);
}
fs::path path = resolve_path(dirname);
if (!fs::is_directory(path)) {
@ -214,7 +214,7 @@ static int l_file_list(lua::State* L) {
return 1;
}
static int l_file_gzip_compress(lua::State* L) {
static int l_gzip_compress(lua::State* L) {
std::vector<ubyte> bytes;
int result = read_bytes_from_table(L, -1, bytes);
@ -233,7 +233,7 @@ static int l_file_gzip_compress(lua::State* L) {
}
}
static int l_file_gzip_decompress(lua::State* L) {
static int l_gzip_decompress(lua::State* L) {
std::vector<ubyte> bytes;
int result = read_bytes_from_table(L, -1, bytes);
@ -252,7 +252,7 @@ static int l_file_gzip_decompress(lua::State* L) {
}
}
static int l_file_read_combined_list(lua::State* L) {
static int l_read_combined_list(lua::State* L) {
std::string path = lua::require_string(L, 1);
if (path.find(':') != std::string::npos) {
throw std::runtime_error("entry point must not be specified");
@ -260,23 +260,32 @@ static int l_file_read_combined_list(lua::State* L) {
return lua::pushvalue(L, engine->getResPaths()->readCombinedList(path));
}
static int l_read_combined_object(lua::State* L) {
std::string path = lua::require_string(L, 1);
if (path.find(':') != std::string::npos) {
throw std::runtime_error("entry point must not be specified");
}
return lua::pushvalue(L, engine->getResPaths()->readCombinedObject(path));
}
const luaL_Reg filelib[] = {
{"exists", lua::wrap<l_file_exists>},
{"find", lua::wrap<l_file_find>},
{"isdir", lua::wrap<l_file_isdir>},
{"isfile", lua::wrap<l_file_isfile>},
{"length", lua::wrap<l_file_length>},
{"list", lua::wrap<l_file_list>},
{"mkdir", lua::wrap<l_file_mkdir>},
{"mkdirs", lua::wrap<l_file_mkdirs>},
{"read_bytes", lua::wrap<l_file_read_bytes>},
{"read", lua::wrap<l_file_read>},
{"remove", lua::wrap<l_file_remove>},
{"remove_tree", lua::wrap<l_file_remove_tree>},
{"resolve", lua::wrap<l_file_resolve>},
{"write_bytes", lua::wrap<l_file_write_bytes>},
{"write", lua::wrap<l_file_write>},
{"gzip_compress", lua::wrap<l_file_gzip_compress>},
{"gzip_decompress", lua::wrap<l_file_gzip_decompress>},
{"read_combined_list", lua::wrap<l_file_read_combined_list>},
{"exists", lua::wrap<l_exists>},
{"find", lua::wrap<l_find>},
{"isdir", lua::wrap<l_isdir>},
{"isfile", lua::wrap<l_isfile>},
{"length", lua::wrap<l_length>},
{"list", lua::wrap<l_list>},
{"mkdir", lua::wrap<l_mkdir>},
{"mkdirs", lua::wrap<l_mkdirs>},
{"read_bytes", lua::wrap<l_read_bytes>},
{"read", lua::wrap<l_read>},
{"remove", lua::wrap<l_remove>},
{"remove_tree", lua::wrap<l_remove_tree>},
{"resolve", lua::wrap<l_resolve>},
{"write_bytes", lua::wrap<l_write_bytes>},
{"write", lua::wrap<l_write>},
{"gzip_compress", lua::wrap<l_gzip_compress>},
{"gzip_decompress", lua::wrap<l_gzip_decompress>},
{"read_combined_list", lua::wrap<l_read_combined_list>},
{"read_combined_object", lua::wrap<l_read_combined_object>},
{NULL, NULL}};