0

Part of code my generates a string, which is then suppose to be used by a function to generated a chuck in VoxelJS.

An example string is "(y == 1)? 1 : 0"

Which I then need to be added to a function like this, eg. "function(x, y, z){return (y == 1)? 1 : 0}"

I thought using eval would change my string to the needed code, like this:

gtest = function(x, y, z){return eval(generationString) };

but I misunderstood how eval is used, and realized I needed to try something else.

If I look at gtest in the JavaScript console it says it's structure is function (x, y, z){return eval(generationString) } when I want it to look like function (x, y, z){return return (y == 1)? 1 : 0}}. Attempting to pass the code containting the eval causes VoxelJS to crash/freeze when it tries to generate new chunks.

How can I convert the string with the javascript code to code in a function in the way I want?

I realize this might be a hard to understand question, sorry about that, I'm not sure how to describe it any other way.

2
  • 1
    Your eval function should have worked, unless eval is not eval. Of course, it's potentially slow if that function is called very often. Commented Feb 25, 2016 at 2:56
  • @Bergi yeah it was being called hundreds of times a second, so it was probably just extremely slow Commented Mar 3, 2016 at 20:12

1 Answer 1

1

I found the answer literally 30 seconds after posting this, use the function() constructor.

Given a string describing a Javascript function, convert it to a Javascript function

gtest = new Function('x', 'y', 'z', 'return ' + generationString);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.