index_object extensions
You can extend index_object
with custom functions as follows:
- Create a Lua function.
- Add the function name to a predefined global variable, which has the
table
type. - Call the function on the
index_object
:index_object:function-name([parameters])
.
There are three predefined global variables:
- Adding to
box_schema.index_mt
makes the function available for all indexes. - Adding to
box_schema.memtx_index_mt
makes the function available for all memtx indexes. - Adding to
box_schema.vinyl_index_mt
makes the function available for all vinyl indexes.
Alternatively, you can make a user-defined function available for only one index
by calling getmetatable(index_object)
and then adding the function name to the
meta table.
Example 1:
The example below shows how to extend all memtx indexes with the custom function:
box.schema.space.create('tester1', { engine = 'memtx' })
box.space.tester1:create_index('index1')
global_counter = 5
-- Create a custom function.
function increase_global_counter()
global_counter = global_counter + 1
end
-- Extend all memtx indexes with the created function.
box.schema.memtx_index_mt.increase_global_counter = increase_global_counter
-- Call the 'increase_global_counter' function on 'index1'
-- to change the 'global_counter' value from 5 to 6.
box.space.tester1.index.index1:increase_global_counter()
Example 2:
The example below shows how to extend the specified index with the custom function with parameters:
box.schema.space.create('tester2', { engine = 'memtx', id = 1000 })
box.space.tester2:create_index('index2')
local_counter = 0
-- Create a custom function.
function increase_local_counter(i_arg, param)
local_counter = local_counter + param + i_arg.space_id
end
-- Extend only the 'index2' index with the created function.
box.schema.memtx_index_mt.increase_local_counter = increase_local_counter
meta = getmetatable(box.space.tester2.index.index2)
meta.increase_local_counter = increase_local_counter
-- Call the 'increase_local_counter' function on 'index2'
-- to change the 'local_counter' value from 0 to 1005.
box.space.tester2.index.index2:increase_local_counter(5)