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.

Keith M
  • 1,199
  • 2
  • 18
  • 38
  • 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. – Bergi Feb 25 '16 at 02:56
  • @Bergi yeah it was being called hundreds of times a second, so it was probably just extremely slow – Keith M Mar 03 '16 at 20:12

1 Answers1

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);
Community
  • 1
  • 1
Keith M
  • 1,199
  • 2
  • 18
  • 38