0

I have a program in which part of its code has to be modified constantly:

VAR = 'math.sin(x*y)*math.sin(x*y)'

while (x <=  vfinal) and (y <= vfinal):
    v1 = bm.verts.new((round(x,3),round(y,3),VAR))
    x = x + precision
    v2 = bm.verts.new((round(x,3),round(y,3),VAR))
    y = y + precision
    x = x - precision
    v3 = bm.verts.new((round(x,3),round(y,3),VAR))
    x = x + precision
    v4 = bm.verts.new((round(x,3),round(y,3),VAR))
    bm.faces.new((v1,v2,v4,v3))
    y = y - precision
    if (round(x,1) == vfinal):
        y = y + precision
        x = vinicial

Since math.sin(x*y)*math.sin(x*y) appears 4 times (possibly more once I expand the program), I want to easily change the program by changing whats stored in VAR.

So far I tried making VAR a string, which gives an error because bm.verts.new wont accept strings. Also tried removing the ' ' in VAR, to make it a number, but this won't give the desired result further down because x and y change constantly. The only thing that worked was writing math.sin(x*y)math.sin(xy) 4 times, but its tedious and im lazy.

Is there any way to do what I want? if not, what should I do?

1
  • Why wouldn't you put it in a function, and change the function? Commented Aug 14, 2017 at 18:57

1 Answer 1

4

Rather than trying to dynamically execute code, you can make VAR a function:

VAR = lambda x, y: math.sin(x * y) * math.sin(x * y)

or if you prefer a vanilla function:

def VAR(x, y):
    return math.sin(x * y) * math.sin(x * y)

You can then reuse the logic by calling the function. For example:

v1 = bm.verts.new((round(x,3),round(y,3),VAR(x, y)))
Sign up to request clarification or add additional context in comments.

6 Comments

Might suggest a PEP-8-compliant name -- and maybe a longer-form definition.
@kindall Yes thanks, I was in the process of updating
@CharlesDuffy Yeah, you're probably right. I was going to suggest that but was hesitant to modify the OP's code to much with explaining why. I'll update.
Tried doing that, now I get TypeError: <lambda>() missing 2 required positional arguments: 'x' and 'y'
@tacofisher Sorry, forgot to pass x and y to VAR. Now it should work.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.