如何从用户处接收键和值,然后将它们一起分配

** 实际上,我正在开发一个程序,用户输入包含名称和数字的字符串,比如Denial 40,我必须将其存储在一个表中,其中Denial作为键,40作为值,以便我可以对表进行进一步处理。 **

local class = {}
  for i=1,N or 0    --N enter by user no. of classmember
    local name=io.read() --takes the key
    local credit = io.read("*n","*l")--takes the credit as value

    class[name] = credit --assign the credit to the key

  end
点赞
用户6632736
用户6632736

我建议这样:

local credits = {}

while true do
    io.write '请输入姓名和信用额度,或只需按Enter键即可完成:'
    local name, credit = io.read():match('^([^%d%s]+)%s*(%d+)$')
    if name then
        credits[name] = tonumber(credit)
    else
        break
    end
end

-- 展示信用额度:
for name, credit in pairs(credits) do
    print(name .. '的信用额度为' .. tostring(credit))
end
  • 用户将被提示在无限循环中输入包含姓名和数字的字符串。它只有在用户输入空或无法解析的字符串时才会终止。
    • 终止循环的条件不在其标题中 (在 whileuntil 后面),因为它相当复杂,涉及打印邀请并返回两个变量,这些变量在循环体中需要。在简单情况下,这可能不是最佳选择 (另外,跟 C 或 PHP 不同,Lua 中的赋值不是表达式,不返回值),
    • 但是请参见下面的更新!
  • 用户的输入立即用正则表达式解析为两个_捕获组_。
    • [^%d%s] 表示既不是数字也不是空格 (我们不希望姓名带有空格); %s,空白符; %d,数字; +,一个或多个。
  • 如果 name 是非 nil 的,也就是真的,credit 的值将记录在以 name 为键的 credits 中。
  • name (和 credit) 是 nil 时,这个循环就会终止。

更新:这是一种更优雅但略微晦涩的解决方案,基于泛型 for

local credits = {}

local function get_credit()
    io.write '请输入姓名和信用额度,或只需按Enter键即可完成:'
    return io.read():match('^([^%d%s]+)%s*(%d+)$')
end

for name, credit in get_credit do -- 注意这里没有 ()
    credits[name] = tonumber(credit)
end

-- 展示信用额度:
for name, credit in pairs(credits) do
    print(name .. '的信用额度为' .. tostring(credit))
end
2020-10-11 15:25:48