spacepup90
spacepup90

Reputation: 7

Need help stacking or chaining functions together

Im wondering how i can get something like this to work:

Test ={}

function Test:returnNumber5 ()
return 5 
end

function Test:add5( num ) 
return num + 5 
end


function randumFunction()
local num = Test:returnNumber5():add5() 
if num == 10 then

print(num)

end 
end

Im looking to stack or chain together code:

Test:returnNumber5():add5():add5():add5()

I dont understand how to setup long chains of functions. I understand how to call them and get them to do what i want when modding other games but dont know why its not working for my game. I put the test code above into my game and it just crashes my game with no details Using Love2D framework

Please help if u can Thanks!

Upvotes: 1

Views: 110

Answers (1)

Leszek Mazur
Leszek Mazur

Reputation: 2531

First of all, you need constructor to object creation:

Test = {}

function Test:new()
  local o = {}
  setmetatable(o, self)
  self.__index = self
  return o
end

Second thing is to return self if you want use form object:doSomething():doSomethingElse().

Test = {}

function Test:new()
  local o = {}
  setmetatable(o, self)
  self.__index = self
  return o
end

function Test:setNumber5()
  self.num = 5
  return self
end

function Test:add5() 
  self.num = self.num + 5
  return self
end

function Test:value() 
  return self.num
end


function randumFunction()
  local num = Test:new():setNumber5():add5():value()
  
  if num == 10 then
    print(num)
  end 
end

Upvotes: 2

Related Questions