如何修复“尝试连接表和字符串”?

时间:2014-02-16 17:16:13

标签: lua concatenation lua-table

前几天我问了一个与此类似的问题,但是又出现了另一个错误“尝试连接表和字符串”

local questions={
    EN={
        Q2={"Who is the lead developer of Transformice?","Tigrounette"},
        Q4={"What is Eminem's most viewed song on youtube?","I love the way you lie"},
        Q6={"What is the cubic root of 27?","3"},
        Q8={"What are the first 3 digits of Pi","3.141"},
        Q10={"What is the most populated country?","China"},
        Q12={"What is the plural of the word 'Person'?","People"},
        Q14={"Entomology is the science that studies ...?","Insects"},
        Q16={"Who was the creator of the (bot ran) minigame fight?","Cptp"},
        Q18={"The ozone layer restricts ... radiation","Ultraviolet"},
        Q20={"Filaria is caused by ...","Mosquitos"}
    }
local main = questions.EN["Q"..math.random(1,20)].."%s" -- bug here
local current_answer_en = string.gsub(current_question_en,1,2)

1 个答案:

答案 0 :(得分:2)

questions.EN["Q"..math.random(1,20)]是什么类型的对象?比较随机是15,什么类型的对象是questions.EN["Q6"]?它是一个{"What is the cubic root of 27?","3"},它是一个表,Lua不知道如何与字符串连接(在您的情况下为"%s")。如果要与此表的第一项连接,则

local main = questions.EN["Q"..math.random(1,20)][1] .. "%s"

但请注意,您需要我在math.random function with step option?中发布的“随机步骤”功能,否则您可以得到表EN["Q"..something]为零(如果随机数是奇数,在您发布的代码中)。

请注意您确定要对current_question_en进行的操作,但如果您尝试提取问题并回答,则可以执行以下操作:

local QA = questions.EN["Q"..math.random(1,20)] -- this is a table
local question, answer = QA[1], QA[2]

另一个选择是你像这样构建你的表:

local questions={
    EN={
        Q2={q="Who is ..?",   a="Tigrounette"},
        Q4={q="What is ...?", a="I love the way you lie"},
        ...
    }
}

然后你可以使用

local QA = questions.EN["Q"..math.random(1,20)] -- this is a table
print("The question:", QA.q)
print("The answer:", QA.a)

不确定您要对string.gsub做什么,但它不会将整数作为第2和第3个参数。