Page 1 of 1

Trouble using stencil()

Posted: Sun Dec 11, 2022 1:45 pm
by Bobble68
Hi there,

I'm trying to use love.graphics.stencil(), but am having trouble trying to get it to do exactly what I want.

I'm able to successfully use the function like this

Code: Select all

love.graphics.stencil(stencilFunction, "replace", 1)
However, I want to be able to pass arguments into stencilFunction(), like this

Code: Select all

love.graphics.stencil(stencilFunction(exampleArg), "replace", 1)
Which gives me this error

Code: Select all

bad argument #1 to 'stencil' (function expected, got nil)
Anyone know what I'm doing wrong? I'm guessing I'm misunderstanding how lua works in regards to passing functions.

Re: Trouble using stencil()

Posted: Sun Dec 11, 2022 2:02 pm
by GVovkiv
when you use function as:

Code: Select all

superFunction()
It means that you will call this function, get result (with return keyword, or nil if there is nothing to return)
If you need to pass function, you do:

Code: Select all

functionThatExpectFunctionArgument(superFunction)
In your case, you pass stencilFunction() to love.graphics.stencil(stencilFinction(exampleArgs)), which returns nil (since, i guess, your stencilFunction doesn't return anything).
If you need to pass arguments to your stencilFunction, you might try use value for that outside:

Code: Select all

local argForStencil = 0
local function stencilFunction()
   local arg = argForStencil
   if arg == 0 then
   love.graphics.rectangle("fill", 225, 200, 350, 300)
   elseif arg == 1 then
   love.graphics.rectangle("fill",0, 0, 350, 300)
   end
end

function love.draw()
    love.graphics.stencil(stencilFunction, "replace", 1)
   end
And then change value depending on situation. You also might try to do this with closures or metatables, or some oop shenanigans.

Also it might possible to do like this:

Code: Select all

local decideStencil = function(arg, x, y)
	if arg == 1 then
		return function()
		      love.graphics.rectangle("fill", x, y, 350, 300)
		end
	elseif arg == 2 then
	        return function()
		      love.graphics.rectangle("fill", x, y, 100, 100)
		end
	end
end
love.graphics.stencil(decideStencil(1, 100, 100), "replace", 1)