E
E
Evgeny Ivanovich2019-10-29 11:24:41
Lua
Evgeny Ivanovich, 2019-10-29 11:24:41

Why is there a registry in lua?

In general, the essence of the question is this, there is a function debug.getregistry (). The function returns a table, the question is, what role does this table play in the interpreter?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
Q
q2zoff, 2019-10-29
@q27off

Some data abstractions cannot be stored in pure C code. - Their implementations are "hidden" behind a fancy API. Such data include, for example, lua tables.
Typically, a table at index LUA_REGISTRYINDEX is used to store user library metatables. For example, during library initialization, a metatable is created:

luaL_newmetatable(L, LIBNAME); // создаем метатаблицу на стэке
// ... - какой-то код, наполняющий созданную таблицу
lua_rawsetp(L, LUA_REGISTRYINDEX, (void*)METAKEY); // устанавливаем метатаблицу по уникальному ключу

Then, when generating a new library object, it is set to the previously created metatable:
int object_new(lua_State *L)
{
    char *ud = lua_newuserdata(L, UDSIZE); // создаем новый объект
    lua_rawgetp(L, LUA_REGISTRYINDEX, (void *)METAKEY); // извлекаем ранее созданную метатаблицу
    lua_setmetatable(L, -2); // устанавливаем метатаблицу для созданного объекта
    return 1;
}

Z
zed, 2019-10-29
@zedxxx

This is detailed in the documentation: https://www.lua.org/manual/5.3/manual.html#4.5

Lua provides a registry, a predefined table that is available to C code to store any Lua value. The registry table is always located at the LUA_REGISTRYINDEX pseudo-index. Any C library can store data in this table, but it must take care of choosing unique keys to avoid collisions with other libraries. Usually, you should use as a key a string containing the name of the library, or light userdata with the address of the C object in your code, or any Lua object created by your code. Like variable names, keys that begin with an underscore followed by an uppercase letter are reserved for Lua.
Integer keys in the registry are used by the reference mechanism (see luaL_ref) and some predefined values. Therefore, integer keys should not be used for other purposes.
When you create a new Lua context, its registry contains some predefined values. These predefined values ​​are indexed by integer keys defined as constants in lua.h. The following constants are defined:
Also, there is a small usage example in Programming in Lua: https://www.lua.org/pil/27.3.1.html

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question