【发布时间】:2019-09-18 06:15:33
【问题描述】:
我使用 Lua 制作了一个表格和游戏脚本。概念如下: 从用户猜测从表中获取的随机词(第一个索引)开始,如果用户回答正确,则显示下一个随机词(下一个表条目),依此类推,直到显示所有表条目。
如何在 Lua 中使用 for..do 使其循环?
我当前的代码:
WordTable = {
{lv = 1, v_random = "LEOHL", v_word = "HELLO"},
{lv = 1, v_random = "GEEINN", v_word = "ENGINE"},
{lv = 1, v_random = "TECHA", v_word = "CHEAT"},
{lv = 2, v_random = "dwIl prEARmgorm", v_word = "WILD PROGRAMMER"},
{lv = 2, v_random = "abDEKory deEPRss", v_word = "KEYBOARD PRESSED"},
}
function tablelength(T)
local count = 0
for _ in pairs(T) do count = count + 1 end
return count
end
function getTypingWord()
local score = 0
local point = 0
index = 1
count = tablelength(WordTable)
tab = WordTable[index]
for index=1,count do
local rdmWord = tab.v_random
local crtWord = tab.v_word
labelWrd.Caption = rdmWord
local mcWord = string.upper(edtWrd.Text)
-- edtWrd is a text box
if mcWord == '' or mcWord == nil then return nil end
if mcWord == crtWord then
showMessage('Great, the answer is '..crtWord)
edtWrd.Text = ''
point = point+1
score = point*200
labelLevel.Caption = 'True : '..point -- a label
labelScore.Caption = 'Score : '..score -- a label
index = index + 1
tab = WordTable[index]
else
showMessage('Try Again')
edtWrd.Text = ''
end
end
end
-- wait user answer till ENTER key has pressed
edtWrd.OnKeyPress = function(sender, key)
if isKeyPressed(VK_RETURN) then getTypingWord() end
return key
end
【问题讨论】:
-
您是在寻找真正的随机循环,还是只是一个一个地迭代?所以
for i = 1, #WordTable do可能是你需要的。观看this。 -
@csaar:我需要根据用户输入的条件逐一迭代,例如:WordTable 的第一个索引是“LEOHL”,用户需要猜测正确的词是什么,在这种情况下,是“你好”。因此,当用户在提供的文本框上键入“HELLO”并按回车键时,WordTable 索引将进入下一个索引(下一个单词),依此类推,直到所有单词都显示出来。用户猜错字没关系,我有一个计时器来处理。