Created
April 20, 2012 22:53
-
-
Save Scriptor/2432470 to your computer and use it in GitHub Desktop.
Stack lang for anarchy channel
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
def onMessage(name, message): | |
funcs = {} | |
if message[0] != '>': | |
return None | |
def do(st): | |
block = st.pop() | |
evaluate(block, st) | |
return st.pop() | |
def if_func(st): | |
else_block = st.pop() | |
if_block = st.pop() | |
cond = st.pop() | |
if cond: | |
evaluate(if_block, st) | |
else: | |
evaluate(else_block, st) | |
return st.pop() | |
def def_func(st): | |
body = st.pop() | |
name = st.pop() | |
def do_func(st): | |
evaluate(body, st) | |
return st.pop() | |
funcs[name] = do_func | |
return st.pop() | |
funcs = { | |
'+': lambda st: st.pop() + st.pop(), | |
'-': lambda st: st.pop() - st.pop(), | |
'*': lambda st: st.pop() * st.pop*(), | |
'/': lambda st: st.pop() / st.pop(), | |
'pop': lambda st: st.pop() and st.pop(), | |
'do': do, | |
'if': if_func, | |
'def': def_func, | |
} | |
words = [] | |
word = "" | |
for i,c in enumerate(message[1:]): | |
if i == len(message) - 2: | |
word += c | |
if c.strip() == '' or i == len(message)-2: | |
try: | |
float(word) | |
word = float(word) | |
except ValueError: | |
pass | |
finally: | |
words.append(word) | |
word = "" | |
else: | |
word += c | |
def evaluate(words, st=[]): | |
in_block = False | |
blocks = [st] | |
for word in words: | |
if isinstance(word, list): | |
st.append(word) | |
elif not in_block and word == 'say': | |
print(st.pop()) | |
elif word == '[': | |
in_block = True | |
blocks.append([]) | |
st = blocks[-1] | |
elif word == ']': | |
block = blocks.pop() | |
st = blocks[-1] | |
st.append(block) | |
if len(blocks) == 1: | |
in_block = False | |
elif not in_block and funcs.has_key(word): | |
st.append(funcs[word](st)) | |
else: | |
st.append(word) | |
evaluate(words) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment