Permalink
Cannot retrieve contributors at this time
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
LoLa/examples/lola/forth.lola
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
55 lines (47 sloc)
1.35 KB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// A small example implementing a language similar to Forth | |
// https://en.wikipedia.org/wiki/Forth_(programming_language) | |
// must be declared before it's used anywhere in the script | |
const binary_operators = "+-*/%"; | |
RunForth("1 2 + 3 * 4 - ="); | |
Print(RunForth("1 2 +")); | |
// Applies a singe-character binary operator to the given stack | |
function ApplyBinOp(stack, op) | |
{ | |
const l = Length(stack); | |
const lhs = stack[l - 2]; | |
const rhs = stack[l - 1]; | |
var result; | |
if(op == "+") result = lhs + rhs; | |
else if(op == "-") result = lhs - rhs; | |
else if(op == "*") result = lhs * rhs; | |
else if(op == "/") result = lhs / rhs; | |
else if(op == "%") result = lhs % rhs; | |
var new_stack = Slice(stack, 0, l - 1); | |
new_stack[l - 2] = result; | |
return new_stack; | |
} | |
function RunForth(script, trace) | |
{ | |
const items = Split(script, " ", true); | |
var stack = [ ]; | |
for(command in items) | |
{ | |
const l = Length(stack); | |
if(IndexOf(binary_operators, command) != void) { | |
stack = ApplyBinOp(stack, command); | |
} | |
else if(command == "=") { | |
const top = stack[l - 1]; | |
stack = Slice(stack, 0, l - 1); | |
Print(top); | |
} | |
else { | |
stack = stack + [ StringToNum(command) ]; | |
} | |
if(trace == true) // don't do it on false or void | |
Print(command, " -> ", stack); | |
} | |
const len = Length(stack); | |
if(len > 0) | |
return stack[len - 1]; | |
} |