Прочие компоненты пакета | Tarantool
Документация на русском языке
поддерживается сообществом

Прочие компоненты пакета

All the Tarantool modules are, at some level, inside a package which, appropriately, is named package. There are also miscellaneous functions and variables which are outside all modules.

Имя Назначение
tonumber64() Конвертация строки или Lua-числа в 64-битное целое число
dostring() Анализ и выполнение произвольного Lua-кода
package.path Get file paths used to search for Lua modules
package.cpath Get file paths used to search for C modules
package.loaded Show Lua or C modules loaded by Tarantool
package.searchroot Get the root path for a directory search
package.setsearchroot Set the root path for a directory search
tonumber64(value)

Конвертация строки или Lua-числа в 64-битное целое число. Входное значение может быть выражено десятичным, двоичным (например, 0b1010) или шестнадцатеричным (например, -0xffff) числом. Результат может использоваться в арифметике, причем скорее в 64-битной целочисленной арифметике, а не в арифметике в системе с плавающей запятой. (Операции с неконвертированными Lua-числами выполняются в арифметике в системе с плавающей запятой.) Функция tonumber64() в Tarantool является глобальной.

Пример:

tarantool> type(123456789012345), type(tonumber64(123456789012345))
---
- number
- number
...
tarantool> i = tonumber64('1000000000')
---
...
tarantool> type(i), i / 2, i - 2, i * 2, i + 2, i % 2, i ^ 2
---
- number
- 500000000
- 999999998
- 2000000000
- 1000000002
- 0
- 1000000000000000000
...

Warning: There is an underlying LuaJIT library that operates with C rules. Therefore you should expect odd results if you compare unsigned and signed (for example 0ULL > -1LL is false), or if you use numbers outside the 64-bit integer range (for example 9223372036854775808LL is negative). Also you should be aware that type(number-literal-ending-in-ULL) is cdata, not a Lua arithmetic type, which prevents direct use with some functions in Lua libraries such as math. See the LuaJIT reference and look for the phrase «64 bit integer arithmetic». and the phrase «64 bit integer comparison». Or see the comments on Issue#4089.

dostring(lua-chunk-string[, lua-chunk-string-argument ...])

Анализ и выполнение произвольного Lua-кода. Данная функция используется преимущественно для определения и выполнения Lua-кода без необходимости внесения изменений в глобальное Lua-окружение.

Параметры:
  • lua-chunk-string (string) – Lua-код
  • lua-chunk-string-argument (lua-value) – ноль или другие скалярные значения, которые заменяются или к которым прибавляются значения.
возвращает:

то, что возвращает Lua-код.

Возможные ошибки: Ошибка компиляции появляется как Lua-ошибка.

Пример:

tarantool> dostring('abc')
---
error: '[string "abc"]:1: ''='' expected near ''<eof>'''
...
tarantool> dostring('return 1')
---
- 1
...
tarantool> dostring('return ...', 'hello', 'world')
---
- hello
- world
...
tarantool> dostring([[
         >   local f = function(key)
         >     local t = box.space.tester:select{key}
         >     if t ~= nil then
         >       return t[1]
         >     else
         >       return nil
         >     end
         >   end
         >   return f(...)]], 1)
---
- null
...
package.path

Get file paths used to search for Lua modules. For example, these paths are used to find modules loaded using the require() directive.

See also: package.searchroot()

package.cpath

Get file paths used to search for C modules. For example, these paths are used to find modules loaded using the require() directive.

See also: package.searchroot()

package.loaded

Show Lua or C modules loaded by Tarantool, so that their functions and members are available. loaded shows both pre-loaded modules and modules added using the require() directive.

See also: package.searchroot()

package.searchroot()

Return the current search root, which defines the path to the root directory from which dependencies are loaded. By default, the search root is the current directory.

Примечание

The current directory is obtained using debug.sourcedir().

Example

Suppose the application has the following structure:

/home/testuser/myapp
├── .rocks/share/tarantool/
│   └── foo.lua
├── init.lua
└── modules
    └── bar.lua

In this case, modules are placed in the same directory as the application initialization file. If you run the application using the tarantool command from the myapp directory, …

/home/testuser/myapp$ tarantool init.lua

… the search root is /home/testuser/myapp and Tarantool finds all modules in this directory automatically. This means that to load the foo and modules.bar modules in init.lua, you only need to add the corresponding require directives:

-- init.lua --
require('foo')
require('modules.bar')

Starting with 2.11.0, you can also run the application using the tarantool command from the directory other than myapp:

/home/testuser$ tarantool myapp/init.lua

In this case, the path to the initialization file (/home/testuser/myapp) is added to search paths for modules.

To load modules placed outside of the path to the application directory, use package.setsearchroot().

package.setsearchroot([search-root])

Set the search root, which defines the path to the root directory from which dependencies are loaded. By default, the search root is the current directory (see package.searchroot()).

Параметры:
  • search-root (string) – a relative or absolute path to the search root. If search-root is a relative path, it is expanded to an absolute path. You can omit this argument or set it to box.NULL to reset the search root to the current directory.

Example

Suppose external modules are stored outside the application directory, for example:

/home/testuser/
├── myapp
│   └── init.lua
└── mymodules
    ├── .rocks/share/tarantool/
    │   └── foo.lua
    └── modules
        └── bar.lua

In this case, you can specify the /home/testuser/mymodules path as the search root for modules in the following way:

-- init.lua --
package.setsearchroot('/home/testuser/mymodules')

Then, you can load the foo and bar modules using the require() directive:

-- init.lua --
require('foo')
require('modules.bar')
Нашли ответ на свой вопрос?
Обратная связь