thecrentist
thecrentist

Reputation: 1271

Lua error: string expected, got nil --- bad argument #2

It is a script in Lua for a game in Corona SDK. At first the (Old code) was very inefficient and I had to manually create each math problem manually, with the (New code) with the help from someone on SO I got that.

In the console I get this error now:

line 93: local questionText = display.newText(questionGroup, questions[currentQuestion].question, 0,0, chalkfFont, 34 )

game.lua:93: bad argument #2 to 'newText' (string expected, got nil)

--mathQuestions.lua (Old code)
local M = {}
M["times"] = {
    {
        question="6 x 5",  --The question.
        answers={"30", "11", "29", "20"},  --Array of possible answers.
        answer=1   --Which one from the above array is the correct answer.
    },
}
return M

--mathQuestions.lua (New code)
local rnd = function (x) return math.random(1,x) end
M.times = {}
local numQuestions = 10 -- how many questions in your database
for i=1,numQuestions do
    local obj =
    {
        left=math.random(1,10),
        right=math.random(1,10),
        answers={rnd(100), rnd(100), rnd(100), rnd(100)},
        answerIndex=rnd(4) -- will override answer[answerIndex] later
    }
    obj.answer = obj.left * obj.right
    obj.answers[obj.answerIndex] = obj.answer
    M.times[i] = obj
end

Any ideas on what the problem is and how to fix it? Thanks.

Upvotes: 2

Views: 8629

Answers (1)

Oliver
Oliver

Reputation: 29621

Line 93 has "questions[currentQuestion].question": each item in questions table is a table with field "left", "right" etc, but no field "question" which you access in line 93. In your loop where you define questions add a line before "obj.answer =":

obj.question = string.format("%s x %s", left, right)

Upvotes: 2

Related Questions