Home > Blockchain >  How can I chain function call in lua?
How can I chain function call in lua?

Time:12-13

I am trying to make a function to chain functions call. However it is not working. It should be able to print out the value after doing the sum without any issues.

Here is my first attempt:

local _ = {}
function _.add(x, y) return x   y end
function _.lt(x, y) return x < y end

function _.chain(value)
    local mt = {
        __newindex = function(t, k, v)
            t._value = _[k](t._value, v)
        end
    }
    local chain = {
        _value = value,
        value = function(self)
            return self._value
        end
    }
    chain = setmetatable(chain, mt)
    return chain
end

local value = chain(2).add(5)
print(value)

This solution is not working because it should be able to localize the function through the __newindex metatable . Instead of localizing the function, it's throwing me a error saying the following message:

lua: main.lua:21: attempt to call a nil value (method 'add')
stack traceback:
    main.lua:21: in main chunk
    [C]: in ?

My second attempt at solving this issue was by using no metamethod what's so ever:

local _ = {}
function _.add(x, y) return x   y end
function _.lt(x, y) return x < y end

function _.chain(value)
    local t = {
        _value = value;
        value = function (self)
            return self._value
        end
    }
    -- merge methods in t
    for k, v in pairs(_) do
        if type(v) == "function" then
            t[k] = function (self, ...)
                local result = v(self._value, ...)
                if result ~= self._value then
                    self._value = result
                end
                return self
            end
        end
    end
    
    return t
end
local sum = _.chain(2):add(5):value()
print(sum)

This attempt doesn't work because it's printing out nil instead of 7.

CodePudding user response:

In your first attempt you are not adding new fields to the table chain so the method __newindex is never called, in your second attempt, I don't know what you did wrong because it worked to me, I did:

local sum = _.chain(2):add(5):value()
print(sum)

and printed 7

local sum = _.chain(2):add(5):add(3):value()
print(sum)

and printed 10

local sum = _.chain(2):add(5):add(3):add(7):value()
print(sum)

and printed 17

  • Related