开发者

Lua from string to action?

I just got homework to create a lua menu which is as small as possible, and as user friendly as possible.

Currently it's 32 lines long and it's being used like this:

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

I'd like to make it so function use() would be replaced with

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

But now there's the problem, that I can't use any of those actions when they're strings. Is there any way to just "开发者_开发问答remove" the quotation marks?

I already did customize the use function to this:

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

Of course there's no such command as "toaction", but this is what I'm looking for, is it possible to make that, or do I just have to stick with my current use function?

Edit: I just realized that it could be done by writing the text's from menu_actions table into a .lua file and then remove quotation marks, and then just run the lua file and remove it after menu is being shut down... But that's slow, any better ideas?

Edit2: SOLVED

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

Thanks, that works! :D But then again, I could just replace the whole toaction() with loadstring()...

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

But thanks, didn't know there was function called loadstring >.<


Try this:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜