Lua从字符串到动作?

我刚刚得到了一个作业,要创建一个尽可能小且用户友好的lua菜单。

目前它有32行,使用方式如下:

menu_name = "Mahi's Lua Menu Template v1"
menu_items = {
    "Move menu to left",
    "Move menu to right",
    "Reset menu position",
    "Exit menu"
}
function use(item)
    if item==1 then menupos=menupos-1
    elseif item==2 then menupos=menupos+1
    elseif item==3 then menupos=3
    elseif item==4 then quit=true end
end

我想将函数use()替换为

menu_actions = {
    "menupos=menupos-1",
    "menupos=menupos+1",
    "menupos=3",
    "quit=true"
}

但现在有一个问题,当它们是字符串时,我无法使用其中任何一个操作。有没有办法仅“删除”引号?

我已经将use函数定制为此:

function use()
    for i=1,#menu_actions do
        if i==selection then
            toaction(menu_actions[i])
        end
    end
end

当然,没有像“toaction”这样的命令,但这就是我要找的,能实现吗?还是我只能坚持当前的使用功能?

编辑:我刚意识到可以通过将menu_actions表中的文本写入.lua文件中,然后删除引号,然后运行lua文件并在关闭菜单后删除它… 但这很慢,还有更好的想法吗?

编辑2:已解决

function toaction(s)
  if _G[s]==nil then _G[s]=loadstring(s) end
  _G[s]()
end

谢谢,这管用!:D但我可以用loadstring()来替换整个toaction()...

function use()
    for i=1,#menu_actions do
        if i==selection then
            loadstring(menu_actions[i])()
        end
    end
end

但感谢您,我不知道有一个名为loadstring()的函数 >。<

原文链接 https://stackoverflow.com/questions/5689353

点赞
stackoverflow用户107090
stackoverflow用户107090

尝试这样做:

function toaction(s)
  if _G[s]==nil then _G[s]=loadstring(s) end
  _G[s]()
end
2011-04-16 20:28:02