如何使用Lua为Corona SDK随机生成数字

时间:2014-02-22 01:40:13

标签: lua corona

我有这个简单的游戏,由此产生数学问题,但由于我必须亲自手动解决所有问题,因此效率非常低。

有没有人比这更了解一些代码或者指导我如何设置它的好教程?谢谢。

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

更新

{
    a = math.random( 1, 20 ),
    b = math.random( 1, 20 ),
    question = a * b,
    answer = math.random( m, n )
}

我认为这会有效,但我在控制台中收到此错误:

mathQuestions.lua:55: attempt to perform arithmetic on global 'a' (a nil value)

更新#2

--mathQuestions.lua
M["times"] = {

    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

}

我收到此错误:

ERROR: Failed to execute new ( params ) function on 'game'

mathQuestions.lua:121: unexpected symbol near 'local'

1 个答案:

答案 0 :(得分:1)

试试这个:

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

唯一棘手的部分是obj.answer:你不能在表定义中进行乘法(比如你更新的问题中的answer = a*b),因为左边和右边(a和b)是全局的那个不存在,如果你做answer = obj.a*obj.b那么你也有问题,即obj尚不存在(尚未创建)。