如何在Corona SDK的Lua中随机生成数字?

我有一个简单的游戏,它会生成一个数学问题,但很低效,因为我必须手动制作所有的问题。

有没有人知道比这更好的代码?或者直接指引我一个建立这个的好教程?谢谢。

local M = {}

M["times"] = {
    {
        question="6 x 5",  -- 问题。
        answers={"30", "11", "29", "20"},  -- 可能答案数组。
        answer=1   -- 上面数组中正确答案。
    },
}

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 -- 在你的数据库中有多少问题
    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) -- 将覆盖answer[answerIndex],以后再说
        }
        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'

点赞
用户869951
用户869951
尝试这个代码:

local rnd = function (x) return math.random(1,x) end M.times = {} local numQuestions = 10 -- 数据库中有多少道题目 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) -- 稍后会覆盖answers[answerIndex]的值 } obj.answer = obj.left * obj.right -- 算出正确答案 obj.answers[obj.answerIndex] = obj.answer -- 将正确答案填入答案列表 M.times[i] = obj -- 将问题对象存入M.times数组 end

```

这里唯一棘手的部分是 obj.answer: 你不能在表定义中进行乘法运算 (例如在你更新的问题中写 answer = a*b),因为 left 和 right (a 和 b) 然后是不存在的全局变量,如果你写上 answer = obj.a*obj.b 那么你也会遇到问题,因为 obj 还不存在 (它还没有被创建)。

2014-02-22 05:27:25