Learn to Code via Tutorials on Repl.it!

← Back to all posts
How To Make A Programming Language In Javascript
h
Battledash2 (79)

Hey There!

I’d bet your here to learn how to make your own programming language using js! (im on mobile so I cant make code blocks :()

This Will NOT Tell You How To Do The HTML and CSS Only The Parser!

Step One:
Create a function called “parse” with argument one named ttp for text to parse, it should look like this:

function parse(ttp) {

}

Ok, great!

Step Two:
We now need to create something to convert the text givin into something computer readable. We're gonn replace every \n that doesnt have a ; before it with a ; then replace ;\n with just ; last we're gonna replace all \n with nothing, here's how:

function parse(ttp) {
ttp = ttp
.replace(/([^;])\n/gm, '$1;')
.replace(/;\n/gm, ';')
.replace(/\n/gm, '');
}

Now our commands are splitted with ;'s so we can split with ; but type our commands with either ; or backspace!

Step Three:
Splitting The Commands So We Can Parse!
We now need to split our code in to an array so our script can understand what to do! We'll do it like this:

function parse(ttp) {
ttp = ttp
.replace(/([^;])\n/gm, '$1;')
.replace(/;\n/gm, ';')
.replace(/\n/gm, '');

let cmds = ttp.split(';');

}

We Now Need To Loop Through It:

function parse(ttp) {
ttp = ttp
.replace(/([^;])\n/gm, '$1;')
.replace(/;\n/gm, ';')
.replace(/\n/gm, '');

let cmds = ttp.split(';');

for(var i = 0; i<cmds.length; i++) {
    // Remove Any Commands That Are Null Or Empty.
	let cmd = cmds[i].split(':');
	for(var x = 0; x<cmd.length; x++) {
		if(cmd[x] == null || cmd[x] == '') {
			cmd.splice(x, 1)
			cmds[i].splice(x, 1)
		}
	}
}

}

Nice!!

Step Four:
We need to check the command now. We can use if(cmd[0] == 'CommandName')

Here's an example:

function parse(ttp) {
ttp = ttp
.replace(/([^;])\n/gm, '$1;')
.replace(/;\n/gm, ';')
.replace(/\n/gm, '');

let cmds = ttp.split(';');

for(var i = 0; i<cmds.length; i++) {
    // Remove Any Commands That Are Null Or Empty.
	let cmd = cmds[i].split(':');
	for(var x = 0; x<cmd.length; x++) {
		if(cmd[x] == null || cmd[x] == '') {
			cmd.splice(x, 1)
			cmds[i].splice(x, 1)
		}
	}
	
	if(cmd[0] == "alert") {
	    if(cmd[1] != null) {
	        alert(cmd[1])
	    } else {
	        console.error("Missing Arg 1")
	    }
	} else if(cmd[0] == "print") {  // adding another command
	    if(cmd[1] != null) {
	        console.log(cmd[1])
	    } else {
	        console.error("Missing Arg 1")
	    }
	} else {
	    console.error("Unknown Command")
	}
}

}

That's all! We can now do this to run the code:

TextInput:
parse(document.querySelector("#inputsId").value)
Normal:
parse("print:hi;alert:quack")

Comments
hotnewtop
Vandesm14 (2644)

You should put your code in code fences like this: