如何在Lua中获取表的第x个键。
2013-2-1 16:7:11
收藏:0
阅读:140
评论:3
现在,我想能够生成一些随机单词。但由于单词是键,所以我该如何选择一些单词,给定dictTableSize的值?谢谢。
点赞
用户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
在加载字典时,为每个单词添加数字索引:
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
评论区的留言会收到邮件通知哦~
推荐文章
- 如何将两个不同的lua文件合成一个 东西有点长 大佬请耐心看完 我是小白研究几天了都没搞定
- 如何在roblox studio中1:1导入真实世界的地形?
- 求解,lua_resume的第二次调用继续执行协程问题。
- 【上海普陀区】内向猫网络招募【Skynet游戏框架Lua后端程序员】
- SF爱好求教:如何用lua实现游戏内调用数据库函数实现账号密码注册?
- Lua实现网站后台开发
- LUA错误显式返回,社区常见的规约是怎么样的
- lua5.3下载库失败
- 请问如何实现文本框内容和某个网页搜索框内容连接,并把网页输出来的结果反馈到另外一个文本框上
- lua lanes多线程使用
- 一个kv数据库
- openresty 有没有比较轻量的 docker 镜像
- 想问一下,有大佬用过luacurl吗
- 在Lua执行过程中使用Load函数出现问题
- 为什么 neovim 里没有显示一些特殊字符?
- Lua比较两个表的值(不考虑键的顺序)
- 有个lua简单的项目,外包,有意者加微信 liuheng600456详谈,最好在成都
- 如何在 Visual Studio 2022 中运行 Lua 代码?
- addEventListener 返回 nil Lua
- Lua中获取用户配置主目录的跨平台方法
可能有两种方法:你可以保留单词的 _数组_,当你需要随机选择一个单词时,只需使用
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 来避免重复扫描结果(此时最好使用第一种方法)。