如何根据列表条目调用函数? [英] How to call a function based on list entry?

查看:44
本文介绍了如何根据列表条目调用函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在进行一项实验,我正在为一种旧的游戏内脚本语言实现一个解释器.这是一种基于第四语言的语言,因此我认为将说明(经过验证和清理)放入一个大列表中会相当容易.

I'm currently working on an experiment where I'm implementing an interpreter for an old in-game scripting language. It's a forth based language, so I figure it would be fairly easy to just have the instructions (once verified and santized) put into a big list.

一旦我得到了列表中的代码,我就会尝试在一次处理一条指令的 for 循环中遍历整个程序.某些项目,如字符串,可以放在一个保存当前堆栈的变量上,这很容易.但我遇到的问题是执行命令.

Once I've got the code in a list, I am trying to iterate through the entire program in a for loop that processes the instructions one at a time. Certain items, like strings, could be placed onto a variable that holds the current stack, which is easy enough. But where I'm stuck is making commands happen.

我有一个很大的有效函数列表,如果有任何指令匹配它们,我希望它调用相关函数.

I have a big list of functions that are valid and I'd like it to where if any instruction matches them, it calls the associated function.

例如,如果我有:

    "Hello, world!" notify

...代码将检查列表中的通知,然后执行通知功能.底线是:如何将字符串转换为函数名称?

...the code would check for notify in a list and then execute the notify function. The bottom line is: How do I translate a string into a function name?

推荐答案

你可以保留一个代码可以调用的函数的字典,然后在需要的时候查找:

You could keep a dictionary of functions the code can call, and then do a look up when you need to:

def notify(s):
    print(s)

d = {"notify": notify}

d["notify"]("Hello, world!")

这篇关于如何根据列表条目调用函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆