JavaScript Eval function with functions and run them

132 views Asked by At

I got run into problem, i am making for three.js in-game editor and i have problems with executing function, but no problems with script executing.

I have tried doing

var codeEnv = function(){}

but it does not matter as it returns always

Uncaught ReferenceError: codeEnv is not defined

My current main javascript code as below:

var env;

function init(){
    initCode();
}

function loadFile() {
    reader.open('get', 'code.txt', true); 
    reader.onreadystatechange = function(){
        if(reader.readyState == 4) {
            editor.innerHTML = reader.responseText;
        }   
    };
    reader.send(null);
}

function replaceAll(find, replace, str) {
    return str.replace(new RegExp(find, 'g'), replace);
}

function initCode(){
    loadFile();
}

var textcode;

function startCode(){
    runCode = false;
    textcode = editor.innerHTML;
    textcode = replaceAll("&lt;", "<", textcode); //replace &lt; with <

    eval(textcode);

    env = codeEnv();

    env.initVars();
    env.init();

    runCode = true;
}

function render(){ // CONSTANTLY CALLED

    if(runCode){
        env.render();
    }

}

And my code.txt:

function codeEnv() {

    tihs.initVars = function() {
        var cubes = [];
        var rows, cols, spacing = 1.3 * 0.5;
        rows = cols = 5;

        for( var r = 0; r < rows; r++ ){
            cubes[r] = [];
        }
    }

    this.init = function() {
        for( var r = 0; r < rows; r++ ){
            for( var c = 0; c < cols; c++ ){
                var cube = new THREE.Mesh(new THREE.BoxGeometry(0.5, 0.1, 0.5), new THREE.MeshBasicMaterial({color: 'white'}));
                cube.position.set( r * spacing, 1, c * spacing);
                cubes[r][c] = cube;
                scene.add(cube);
            }
        }
    }

    this.render = function() {
        i += 0.05;
        for( var r = 0; r < rows; r++ ){
            for( var c = 0; c < cols; c++ ){
                var cube = cubes[r][c];
                cube.position.setY(Math.sin(r/rows + i) / 4 + Math.sin(c/cols + i) / 4 + 1);
            }
        }
    }
}

Editor is html textarea.

These codes just have needed information in them, everything related to problem.

Now it executes the code but initVars doesnt work?

Uncaught TypeError: Cannot read property 'initVars' of undefined

Thank you!

0

There are 0 answers