lua变量名来自用户输入

我正在尝试在lua中制作一个“shell”。

但是主要问题是,我无法从用户输入中定义变量名。 以下是我目前拥有的核心部分。我遇到了what[2] = what[3]下面的评论行的问题。

我如何更好地实现这个?

function lsplit(inputstr, sep)
    if sep == nil then
        sep = "%s"
    end

    local t={} ; i=1
    for str in string.gmatch(inputstr, "([^"..sep.."]+)") do
        t[i] = str
        i = i + 1
    end
    return t
end

function def(what)
    if (what[1] == "end") then
        os.exit(0)
    elseif (what[1] == "help") then
        print("Commander版本0.0")
    elseif (what[1] == "var") then
        what[2] = what[3] --无法定义
    else
        print(“[ERR]不是一个命令!”)
    end
end

whiletruedo
    io.write(“-->”)
    local usr = io.read(“*l”)
    local cmd = lsplit(usr,“”)
    def(cmd)
end
点赞
用户4273199
用户4273199

你正在用第二个参数覆盖第一个参数,而不是创建一个新的变量...试试这段代码!应该可以工作,但没有经过测试!

local userdefinedVars = { }

function lsplit(inputstr)
    words = {}
    for word in s:gmatch("%w+") do
        table.insert(words, word)
    end
end

function def(what)
    if (what[1] == "end") then
        os.exit(0)
    elseif (what[1] == "help") then
        print("Commander version 0.0")
    elseif (what[1] == "var") then
        -- 这就是你如何把你的事情做好!
        userdefinedVars[what[2]] = what[3]
    else
        print("[ERR] 不是命令!")
    end
end

while(true) do
    io.write("--> ")
    local usr = io.read("*line")
    local cmd = lsplit(usr)
    def(cmd)
end
2016-02-10 15:09:43