Lua表错误?
我正在做一种“测验”,我想让脚本从表格中随机挑选一个问题。没有错误,但是当我运行脚本时,没有输出任何内容。似乎for循环只是被跳过了。我在做傻事吗?谢谢你的帮助Lua表错误?,lua,lua-table,Lua,Lua Table,我正在做一种“测验”,我想让脚本从表格中随机挑选一个问题。没有错误,但是当我运行脚本时,没有输出任何内容。似乎for循环只是被跳过了。我在做傻事吗?谢谢你的帮助 local Questions = { Q1 = {"What is the magic word?", "lotion"}, --Q, A Q2 = {"Does anyone love you?", "no"} } for i = 1, #Questions do local number = math.random(1, #Qu
local Questions = {
Q1 = {"What is the magic word?", "lotion"}, --Q, A
Q2 = {"Does anyone love you?", "no"}
}
for i = 1, #Questions do
local number = math.random(1, #Questions)
local q = Questions["Q" .. number][1]
local a = Questions["Q" .. number][2]
print("HI")
print(q .. a)
end
io.read()
#
运算符仅在序列中有效,即类似数组的表,该表使用1
、2
等索引。但是您的表问题不是一个序列。您可以这样做:
local Questions = {
{"What is the magic word?", "lotion"}, --Q, A
{"Does anyone love you?", "no"}
}
for i = 1, #Questions do
local number = math.random(1, #Questions)
local q = Questions[number][1]
local a = Questions[number][2]
print("HI")
print(q .. a)
end
#
运算符仅在序列中有效,即类似数组的表,该表使用1
、2
等索引。但是您的表问题不是一个序列。您可以这样做:
local Questions = {
{"What is the magic word?", "lotion"}, --Q, A
{"Does anyone love you?", "no"}
}
for i = 1, #Questions do
local number = math.random(1, #Questions)
local q = Questions[number][1]
local a = Questions[number][2]
print("HI")
print(q .. a)
end
发生这种情况的原因是没有为索引不是从1开始的序列的表定义长度运算符(#
)。从:
除非给出了\uu len
元方法,否则仅当表是序列时才定义表t
的长度,也就是说,对于某个整数n,其正数字键集等于{1..n}。在这种情况下,n是它的长度
要修复代码,只需删除表键上的“Q”前缀:
local Questions = {
{"What is the magic word?", "lotion"}, --Q, A
{"Does anyone love you?", "no"}
}
for i = 1, #Questions do
local number = math.random(1, #Questions)
local q = Questions[number][1]
local a = Questions[number][2]
print("HI")
print(q .. a)
end
发生这种情况的原因是没有为索引不是从1开始的序列的表定义长度运算符(#
)。从:
除非给出了\uu len
元方法,否则仅当表是序列时才定义表t
的长度,也就是说,对于某个整数n,其正数字键集等于{1..n}。在这种情况下,n是它的长度
要修复代码,只需删除表键上的“Q”前缀:
local Questions = {
{"What is the magic word?", "lotion"}, --Q, A
{"Does anyone love you?", "no"}
}
for i = 1, #Questions do
local number = math.random(1, #Questions)
local q = Questions[number][1]
local a = Questions[number][2]
print("HI")
print(q .. a)
end
@用户3314993:很高兴听到这个消息!记得尽可能地记住。@user3314993:很高兴听到这个消息!记得在你能的时候。