S
S
Sergey2018-08-17 18:52:01
Data processing
Sergey, 2018-08-17 18:52:01

Which of the 2 implementations is more acceptable?

Often there are situations when you can equate some object to a function and this function will be called under certain conditions and parameters, but often this is not enough - you want to hang several functions on 1 object. For this purpose, I wrote 2 implementations. Actually, I want to know which method is more acceptable, I did a test for multiple execution of 4 functions (2 ^ 20 times) - the result is approximately equal in time.

Method one (in depth)

Ф-ции записываются в таблицы, а таблицы одна в другую, у каждой таблицы в метатаблице указано, что при вызове оной выполнится ф-ция и вложенная таблица и так по цепочке: 
local noop = function() end

local storage = {noop}
setmetatable(storage, {__call = function(slf, ...) return slf[1](...) end})
local b = storage

function add(f) -- добавить ф-цию в линию выполнения
    local texe = {noop, f}
    setmetatable(texe, {__call = function(self, ...)
        self[2](...); 
        return self[1](...)
    end})
    b[1] = texe
    b = texe
end

function find(f_obj) -- поиск ф-ции из линии, если нашлась - возвращает её родительскую таблицу (сама найденная ф-ция 2 элемент в таблице)
    local stack, prevStack = storage, storage
    while (type(stack) == "table") do 
        stack = stack[1] 
        if stack[2] == f_obj then
            return prevStack
        end
        prevStack = stack
    end
end -- не громоздкий поиск ф-ции в линии

function del(fun) -- удаление ф-ции из линии
    local a = find(fun)
    a[1] = a[1][1] 
end

Method 2 (wide)
local line = {test, test2, test3, test4}
    
local function iniciator(...)
    for i=1, #line do
        line[i](...)
    end
end

setmetatable(line, {__call = function(slf, ...) return iniciator(...) end})

Специальных ф-ций для получения и удаления ф-ций из таблицы не писал, подразумеваю, что пользователь сам умеет работать с простыми таблицами.

The first method contains more metatables, the connected functions are wrapped in a table with their own metatable and the call of the connected function, the call of the nested table. Everything is tricky and not simple at first glance. The second way is simpler, but there is a loop with a bypass. Interested in the opinions and suggestions of knowledgeable people. 

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question