如何在Lua中获取表的第x个键。

现在,我想能够生成一些随机单词。但由于单词是键,所以我该如何选择一些单词,给定dictTableSize的值?谢谢。

点赞
用户1442917
用户1442917

可能有两种方法:你可以保留单词的 _数组_,当你需要随机选择一个单词时,只需使用 words[math.random(#words)](确保第二个单词与第一个不同)。

另一种方法是使用 next 函数:

function findNth(t, n)
  local val = next(t)
  for i = 2, n do val = next(t, val) end
  return val
end

这将返回 findNth({a = true, b = true, c = true}, 3) 的第三个元素 b(顺序是未定义的)。

你可以通过 memoization 来避免重复扫描结果(此时最好使用第一种方法)。

2013-02-01 17:31:43
用户1208078
用户1208078

这是你使用 table 的权衡。我会在加载后将 table 翻转,这样你就可以通过索引获取单词的引用了。以下是示例代码:

-- 模仿你的词典结构
local t = {
    ["asdf"] = true, ["wer"] = true, ["iweir"] = true, ["erer"] = true
}

-- 翻转表格函数
function invert(tbl)
    local t = {}
    for k, _ in pairs(tbl) do
        table.insert(t, k)
    end
    return t
end

-- 现在随机获取单词
local idx1, idx2 = math.random(dictTableSize), math.random(dictTableSize)
local new_t = invert(t)
local word1, word2 = new_t[idx1], new_t[idx2]
-- word1 和 word2 现在随机获取自你的 `dictTable` 中的单词
2013-02-01 17:34:39
用户501459
用户501459

在加载字典时,为每个单词添加数字索引:

function buildDictionary()
    local path = system.pathForFile("wordlist.txt")
    local file = io.open( path, "r")
    if file then
        local index = 1
        for line in file:lines() do
            dictTable[line] = true
            dictTable[index] = line
            index = index + 1
        end
        io.close(file)
    end
end

现在您可以像这样随机选择单词:

function randomWord()
    return dictTable[math.random(1,#dictTable)]
end

附注:nil 在 Lua 条件语句中等价于 false,因此您可以这样编写 checkWord 函数:

function checkWord(word)
    return dictTable[word]
end

另外,请将字典功能封装到对象中,这样可以减少全局名称空间的污染:

local dictionary = { words = {} }

function dictionary:load()
    local path = system.pathForFile('wordlist.txt')
    local file = io.open( path, 'r')
    if file then
        local index = 1
        for line in file:lines() do
            self.words[line] = true
            self.words[index] = line
            index = index + 1
        end
        io.close(file)
    end
end

function dictionary:checkWord(word)
    return self.words[word]
end

function dictionary:randomWord()
    return self.words[math.random(1,#self.words)]
end

然后您可以这样说:

dictionary:load()
dictionary:checkWord('foobar')
dictionary:randomWord()
2013-02-01 18:26:07