@Pakz Not sure what you’re trying to do, but here’s how you might use set context.
To post code, put 3 tildes ~~~ on a line before and after your code.
Without seeing your complete code I can’t say why you were crashing. The above code didn’t crash my iPad.
viewer.mode=FULLSCREEN
function setup()
im = image(64,64)
setContext(im)
stroke(255)
strokeWidth(2)
for x=0,64 do
line(x,x/2,x,x/2)
--rect(64-x,32-x/2,1,x)
end
setContext()
end
function draw()
background(255, 190, 0)
sprite(im,WIDTH/2,HEIGHT/2)
end
Ah. When I put the code with the line command inside the setup function it does not crash. When outside that function(I put it outside a function on the top of the code) it does crash with the line command but not with the rect command.
I think I need to start putting code like that inside setup()
@Pakz Normally all of your code should be within a function, but with a few exceptions. The setup function needs to run first because there’s a lot things that needs to be initialized so the code runs right.
Before setup is called the graphics context hasn’t been set up yet. Code outside of a function gets called first, so this is why you get issues with calls to graphics based functions
I might add that there are other issues with code outside of functions, some of which can be really confusing. It can be a pain, but I’ve come to think that what works best for me is to do one of two things:
First, most commonly, I’ll put initialization code in setup, or a function called from setup. This is a bit of a pain, because often I forget, and it makes exporting the code more difficult, as the receiving program needs to do the setup stuff.
Second, I might use a “lazy init”, some code like this, in code that needs initialization, such as a class Foo. (The “init” below is the one that defines an instance when you say. Foo().
function Foo:init()
if not FooInitialized then
do the initialization here
FooInitialized = true
end
end
There are, of course, more “clever” ways to do this sort of thing but these two approaches are my most common.
I was just bitten by the “init outside of a function” problem yesterday, so it still happens. I was so sure that this one was OK …
Yeah I can see how this is a pain. The new runtime I’m working on allows you to do anything you want outside of setup, so you can even load images, create shaders, etc. I haven’t tested contexts in that way though.