Trouble using stencil()

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Before you make a thread asking for help, read this.
Post Reply
User avatar
Bobble68
Party member
Posts: 162
Joined: Wed Nov 30, 2022 9:16 pm
Contact:

Trouble using stencil()

Post 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.
Dragon
User avatar
GVovkiv
Party member
Posts: 688
Joined: Fri Jan 15, 2021 7:29 am

Re: Trouble using stencil()

Post 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)
Post Reply

Who is online

Users browsing this forum: Ahrefs [Bot], Bing [Bot], Google [Bot] and 11 guests